packages feed

bindings-portaudio (empty) → 0

raw patch · 24 files changed

+27456/−0 lines, 24 filesdep +basedep +bindings-DSLsetup-changed

Dependencies added: base, bindings-DSL

Files

+ Bindings/PortAudio.hsc view
@@ -0,0 +1,250 @@+{-# OPTIONS_GHC -fno-warn-unused-imports #-}
+#include <bindings.dsl.h>
+#include "../../portaudio/include/portaudio.h"
+module Bindings.PortAudio where
+import Foreign.Ptr
+#strict_import
+
+#synonym_t PaStream, ()
+
+#ccall Pa_GetVersion , IO CInt
+#ccall Pa_GetVersionText , IO CString
+{- typedef int PaError; -}
+#synonym_t PaError , CInt
+{- typedef enum PaErrorCode {
+            paNoError = 0,
+            paNotInitialized = -10000,
+            paUnanticipatedHostError,
+            paInvalidChannelCount,
+            paInvalidSampleRate,
+            paInvalidDevice,
+            paInvalidFlag,
+            paSampleFormatNotSupported,
+            paBadIODeviceCombination,
+            paInsufficientMemory,
+            paBufferTooBig,
+            paBufferTooSmall,
+            paNullCallback,
+            paBadStreamPtr,
+            paTimedOut,
+            paInternalError,
+            paDeviceUnavailable,
+            paIncompatibleHostApiSpecificStreamInfo,
+            paStreamIsStopped,
+            paStreamIsNotStopped,
+            paInputOverflowed,
+            paOutputUnderflowed,
+            paHostApiNotFound,
+            paInvalidHostApi,
+            paCanNotReadFromACallbackStream,
+            paCanNotWriteToACallbackStream,
+            paCanNotReadFromAnOutputOnlyStream,
+            paCanNotWriteToAnInputOnlyStream,
+            paIncompatibleStreamHostApi,
+            paBadBufferPtr
+        } PaErrorCode; -}
+#integral_t enum PaErrorCode
+#num paNoError
+#num paNotInitialized
+#num paUnanticipatedHostError
+#num paInvalidChannelCount
+#num paInvalidSampleRate
+#num paInvalidDevice
+#num paInvalidFlag
+#num paSampleFormatNotSupported
+#num paBadIODeviceCombination
+#num paInsufficientMemory
+#num paBufferTooBig
+#num paBufferTooSmall
+#num paNullCallback
+#num paBadStreamPtr
+#num paTimedOut
+#num paInternalError
+#num paDeviceUnavailable
+#num paIncompatibleHostApiSpecificStreamInfo
+#num paStreamIsStopped
+#num paStreamIsNotStopped
+#num paInputOverflowed
+#num paOutputUnderflowed
+#num paHostApiNotFound
+#num paInvalidHostApi
+#num paCanNotReadFromACallbackStream
+#num paCanNotWriteToACallbackStream
+#num paCanNotReadFromAnOutputOnlyStream
+#num paCanNotWriteToAnInputOnlyStream
+#num paIncompatibleStreamHostApi
+#num paBadBufferPtr
+#ccall Pa_GetErrorText , CInt -> IO CString
+#ccall Pa_Initialize , IO CInt
+#ccall Pa_Terminate , IO CInt
+{- typedef int PaDeviceIndex; -}
+#synonym_t PaDeviceIndex , CInt
+{- typedef int PaHostApiIndex; -}
+#synonym_t PaHostApiIndex , CInt
+#ccall Pa_GetHostApiCount , IO CInt
+#ccall Pa_GetDefaultHostApi , IO CInt
+{- typedef enum PaHostApiTypeId {
+            paInDevelopment = 0,
+            paDirectSound = 1,
+            paMME = 2,
+            paASIO = 3,
+            paSoundManager = 4,
+            paCoreAudio = 5,
+            paOSS = 7,
+            paALSA = 8,
+            paAL = 9,
+            paBeOS = 10,
+            paWDMKS = 11,
+            paJACK = 12,
+            paWASAPI = 13,
+            paAudioScienceHPI = 14
+        } PaHostApiTypeId; -}
+#integral_t enum PaHostApiTypeId
+#num paInDevelopment
+#num paDirectSound
+#num paMME
+#num paASIO
+#num paSoundManager
+#num paCoreAudio
+#num paOSS
+#num paALSA
+#num paAL
+#num paBeOS
+#num paWDMKS
+#num paJACK
+#num paWASAPI
+#num paAudioScienceHPI
+{- typedef struct PaHostApiInfo {
+            int structVersion;
+            PaHostApiTypeId type;
+            const char * name;
+            int deviceCount;
+            PaDeviceIndex defaultInputDevice;
+            PaDeviceIndex defaultOutputDevice;
+        } PaHostApiInfo; -}
+#starttype struct PaHostApiInfo
+#field structVersion , CInt
+#field type , <enum PaHostApiTypeId>
+#field name , CString
+#field deviceCount , CInt
+#field defaultInputDevice , CInt
+#field defaultOutputDevice , CInt
+#stoptype
+#ccall Pa_GetHostApiInfo , CInt -> IO (Ptr <struct PaHostApiInfo>)
+#ccall Pa_HostApiTypeIdToHostApiIndex , <enum PaHostApiTypeId> -> IO CInt
+#ccall Pa_HostApiDeviceIndexToDeviceIndex , CInt -> CInt -> IO CInt
+{- typedef struct PaHostErrorInfo {
+            PaHostApiTypeId hostApiType;
+            long errorCode;
+            const char * errorText;
+        } PaHostErrorInfo; -}
+#starttype struct PaHostErrorInfo
+#field hostApiType , <enum PaHostApiTypeId>
+#field errorCode , CLong
+#field errorText , CString
+#stoptype
+#ccall Pa_GetLastHostErrorInfo , IO (Ptr <struct PaHostErrorInfo>)
+#ccall Pa_GetDeviceCount , IO CInt
+#ccall Pa_GetDefaultInputDevice , IO CInt
+#ccall Pa_GetDefaultOutputDevice , IO CInt
+{- typedef double PaTime; -}
+#synonym_t PaTime , CDouble
+{- typedef unsigned long PaSampleFormat; -}
+#synonym_t PaSampleFormat , CULong
+{- typedef struct PaDeviceInfo {
+            int structVersion;
+            const char * name;
+            PaHostApiIndex hostApi;
+            int maxInputChannels;
+            int maxOutputChannels;
+            PaTime defaultLowInputLatency;
+            PaTime defaultLowOutputLatency;
+            PaTime defaultHighInputLatency;
+            PaTime defaultHighOutputLatency;
+            double defaultSampleRate;
+        } PaDeviceInfo; -}
+#starttype struct PaDeviceInfo
+#field structVersion , CInt
+#field name , CString
+#field hostApi , CInt
+#field maxInputChannels , CInt
+#field maxOutputChannels , CInt
+#field defaultLowInputLatency , CDouble
+#field defaultLowOutputLatency , CDouble
+#field defaultHighInputLatency , CDouble
+#field defaultHighOutputLatency , CDouble
+#field defaultSampleRate , CDouble
+#stoptype
+#ccall Pa_GetDeviceInfo , CInt -> IO (Ptr <struct PaDeviceInfo>)
+{- typedef struct PaStreamParameters {
+            PaDeviceIndex device;
+            int channelCount;
+            PaSampleFormat sampleFormat;
+            PaTime suggestedLatency;
+            void * hostApiSpecificStreamInfo;
+        } PaStreamParameters; -}
+#starttype struct PaStreamParameters
+#field device , CInt
+#field channelCount , CInt
+#field sampleFormat , CULong
+#field suggestedLatency , CDouble
+#field hostApiSpecificStreamInfo , Ptr ()
+#stoptype
+#ccall Pa_IsFormatSupported , Ptr <struct PaStreamParameters> -> Ptr <struct PaStreamParameters> -> CDouble -> IO CInt
+{- typedef void PaStream; -}
+{- typedef unsigned long PaStreamFlags; -}
+#synonym_t PaStreamFlags , CULong
+{- typedef struct PaStreamCallbackTimeInfo {
+            PaTime inputBufferAdcTime;
+            PaTime currentTime;
+            PaTime outputBufferDacTime;
+        } PaStreamCallbackTimeInfo; -}
+#starttype struct PaStreamCallbackTimeInfo
+#field inputBufferAdcTime , CDouble
+#field currentTime , CDouble
+#field outputBufferDacTime , CDouble
+#stoptype
+{- typedef unsigned long PaStreamCallbackFlags; -}
+#synonym_t PaStreamCallbackFlags , CULong
+{- typedef enum PaStreamCallbackResult {
+            paContinue = 0, paComplete = 1, paAbort = 2
+        } PaStreamCallbackResult; -}
+#integral_t enum PaStreamCallbackResult
+#num paContinue
+#num paComplete
+#num paAbort
+
+#callback PaStreamCallback, Ptr () -> Ptr () -> CULong -> Ptr C'PaStreamCallbackTimeInfo -> C'PaStreamCallbackFlags -> Ptr () -> IO <PaStreamCallbackResult>
+
+#callback PaStreamFinishedCallback, Ptr () -> IO ()
+
+#ccall Pa_OpenStream , Ptr (Ptr <PaStream>) -> Ptr <struct PaStreamParameters> -> Ptr <struct PaStreamParameters> -> CDouble -> CULong -> CULong -> <PaStreamCallback> -> Ptr () -> IO CInt
+#ccall Pa_OpenDefaultStream , Ptr (Ptr <PaStream>) -> CInt -> CInt -> CULong -> CDouble -> CULong -> <PaStreamCallback> -> Ptr () -> IO CInt
+#ccall Pa_CloseStream , Ptr <PaStream> -> IO CInt
+#ccall Pa_SetStreamFinishedCallback , Ptr <PaStream> -> Ptr <PaStreamFinishedCallback> -> IO CInt
+#ccall Pa_StartStream , Ptr <PaStream> -> IO CInt
+#ccall Pa_StopStream , Ptr <PaStream> -> IO CInt
+#ccall Pa_AbortStream , Ptr <PaStream> -> IO CInt
+#ccall Pa_IsStreamStopped , Ptr <PaStream> -> IO CInt
+#ccall Pa_IsStreamActive , Ptr <PaStream> -> IO CInt
+{- typedef struct PaStreamInfo {
+            int structVersion;
+            PaTime inputLatency;
+            PaTime outputLatency;
+            double sampleRate;
+        } PaStreamInfo; -}
+#starttype struct PaStreamInfo
+#field structVersion , CInt
+#field inputLatency , CDouble
+#field outputLatency , CDouble
+#field sampleRate , CDouble
+#stoptype
+#ccall Pa_GetStreamInfo , Ptr <PaStream> -> IO (Ptr <struct PaStreamInfo>)
+#ccall Pa_GetStreamTime , Ptr <PaStream> -> IO CDouble
+#ccall Pa_GetStreamCpuLoad , Ptr <PaStream> -> IO CDouble
+#ccall Pa_ReadStream , Ptr <PaStream> -> Ptr () -> CULong -> IO CInt
+#ccall Pa_WriteStream , Ptr <PaStream> -> Ptr () -> CULong -> IO CInt
+#ccall Pa_GetStreamReadAvailable , Ptr <PaStream> -> IO CLong
+#ccall Pa_GetStreamWriteAvailable , Ptr <PaStream> -> IO CLong
+#ccall Pa_GetSampleSize , CULong -> IO CInt
+#ccall Pa_Sleep , CLong -> IO ()
+ LICENSE view
@@ -0,0 +1,8 @@+PortAudio Portable Real-Time Audio Library 
+Copyright (c) 1999-2011 Ross Bencina and Phil Burk
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ bindings-portaudio.cabal view
@@ -0,0 +1,124 @@+name:         bindings-portaudio
+version:      0
+category:     Sound
+
+author:       Fumiaki Kinoshita <fumiexcel@gmail.com>
+maintainer:   Fumiaki Kinoshita <fumiexcel@gmail.com>
+
+license:      BSD3
+license-file: LICENSE
+
+synopsis:     Low-level bindings to portaudio library
+description:
+cabal-version: >= 1.10
+build-type:    Simple
+
+--------------------------------------------------------------------------------
+
+flag WASAPI
+  default: False
+
+flag DirectSound
+  default: False
+
+flag WMME
+  default: False
+
+flag WDMKS
+  default: False
+
+flag MinGW-External
+  default: False
+
+library
+  default-language: Haskell2010
+
+  ghc-options: -Wall -O2
+  if impl(ghc >= 6.8)
+    ghc-options: -fwarn-tabs
+
+  exposed-modules:
+    Bindings.PortAudio
+
+  build-tools:
+    hsc2hs
+
+  build-depends:
+    base          < 5, bindings-DSL == 1.0.*
+
+  include-dirs:
+    portaudio/include
+    portaudio/src/common
+
+  c-sources:
+    portaudio/src/common/pa_allocation.c
+    portaudio/src/common/pa_front.c
+    portaudio/src/common/pa_converters.c
+    portaudio/src/common/pa_process.c
+    portaudio/src/common/pa_cpuload.c
+    portaudio/src/common/pa_ringbuffer.c
+    portaudio/src/common/pa_debugprint.c
+    portaudio/src/common/pa_stream.c
+    portaudio/src/common/pa_dither.c
+    portaudio/src/common/pa_trace.c
+  cc-options: -g -O2
+    -DHAVE_INTTYPES_H=1
+    -DHAVE_MEMORY_H=1
+    -DHAVE_STDINT_H=1
+    -DHAVE_STDLIB_H=1
+    -DHAVE_STRING_H=1
+    -DHAVE_STRINGS_H=1
+    -DHAVE_SYS_STAT_H=1
+    -DHAVE_SYS_TYPES_H=1
+    -DHAVE_UNISTD_H=1
+    -DPA_LITTLE_ENDIAN
+    -DSIZEOF_INT=4
+    -DSIZEOF_LONG=4
+    -DSIZEOF_SHORT=2
+    -DSTDC_HEADERS=1
+
+  if os(linux) || os(freebsd) || os(darwin)
+    pkgconfig-depends: portaudio-2.0
+
+  if os(mingw32) && !flag(MinGW-External)
+    include-dirs:
+      portaudio/src/os/win
+    c-sources:
+      portaudio/src/os/win/pa_win_coinitialize.c
+      portaudio/src/os/win/pa_win_hostapis.c
+      portaudio/src/os/win/pa_win_util.c
+      portaudio/src/os/win/pa_win_waveformat.c
+      portaudio/src/os/win/pa_win_wdmks_utils.c
+      -- portaudio/src/os/win/pa_x86_plain_converters.c
+    extra-libraries: winmm ole32 uuid
+    cc-options: -mthreads
+
+    if flag(WASAPI)
+      include-dirs:
+        portaudio/src/hostapi/wasapi/mingw-include
+      c-sources:
+        portaudio/src/hostapi/wasapi/pa_win_wasapi.c
+      cc-options: -DPA_USE_WASAPI=1
+
+    if flag(DirectSound)
+      include-dirs:
+        portaudio/src/hostapi/dsound
+      c-sources:
+        portaudio/src/hostapi/dsound/pa_win_ds.c
+        portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c
+      cc-options: -DPA_USE_DS=1
+
+    if flag(WMME)
+      c-sources:
+        portaudio/src/hostapi/wmme/pa_win_wmme.c
+      cc-options: -DPA_USE_WMME=1
+
+    if flag(WDMKS)
+      c-sources:
+        portaudio/src/hostapi/wdmks/pa_win_wdmks.c
+      cc-options: -DPA_USE_WDMKS=1
+      extra-libraries: Setupapi
+
+source-repository head
+  type:     git
+  location: https://github.com/fumieval/portaudio-builtin.git
+ portaudio/src/common/pa_allocation.c view
@@ -0,0 +1,243 @@+/*+ * $Id: pa_allocation.c 1097 2006-08-26 08:27:53Z rossb $+ * Portable Audio I/O Library allocation group implementation+ * memory allocation group for tracking allocation groups+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Allocation Group implementation.+*/+++#include "pa_allocation.h"+#include "pa_util.h"+++/*+    Maintain 3 singly linked lists...+    linkBlocks: the buffers used to allocate the links+    spareLinks: links available for use in the allocations list+    allocations: the buffers currently allocated using PaUtil_ContextAllocateMemory()++    Link block size is doubled every time new links are allocated.+*/+++#define PA_INITIAL_LINK_COUNT_    16++struct PaUtilAllocationGroupLink+{+    struct PaUtilAllocationGroupLink *next;+    void *buffer;+};++/*+    Allocate a block of links. The first link will have it's buffer member+    pointing to the block, and it's next member set to <nextBlock>. The remaining+    links will have NULL buffer members, and each link will point to+    the next link except the last, which will point to <nextSpare>+*/+static struct PaUtilAllocationGroupLink *AllocateLinks( long count,+        struct PaUtilAllocationGroupLink *nextBlock,+        struct PaUtilAllocationGroupLink *nextSpare )+{+    struct PaUtilAllocationGroupLink *result;+    int i;+    +    result = (struct PaUtilAllocationGroupLink *)PaUtil_AllocateMemory(+            sizeof(struct PaUtilAllocationGroupLink) * count );+    if( result )+    {+        /* the block link */+        result[0].buffer = result;+        result[0].next = nextBlock;++        /* the spare links */+        for( i=1; i<count; ++i )+        {+            result[i].buffer = 0;+            result[i].next = &result[i+1];+        }+        result[count-1].next = nextSpare;+    }+    +    return result;+}+++PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void )+{+    PaUtilAllocationGroup* result = 0;+    struct PaUtilAllocationGroupLink *links;+++    links = AllocateLinks( PA_INITIAL_LINK_COUNT_, 0, 0 );+    if( links != 0 )+    {+        result = (PaUtilAllocationGroup*)PaUtil_AllocateMemory( sizeof(PaUtilAllocationGroup) );+        if( result )+        {+            result->linkCount = PA_INITIAL_LINK_COUNT_;+            result->linkBlocks = &links[0];+            result->spareLinks = &links[1];+            result->allocations = 0;+        }+        else+        {+            PaUtil_FreeMemory( links );+        }+    }++    return result;+}+++void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group )+{+    struct PaUtilAllocationGroupLink *current = group->linkBlocks;+    struct PaUtilAllocationGroupLink *next;++    while( current )+    {+        next = current->next;+        PaUtil_FreeMemory( current->buffer );+        current = next;+    }++    PaUtil_FreeMemory( group );+}+++void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size )+{+    struct PaUtilAllocationGroupLink *links, *link;+    void *result = 0;+    +    /* allocate more links if necessary */+    if( !group->spareLinks )+    {+        /* double the link count on each block allocation */+        links = AllocateLinks( group->linkCount, group->linkBlocks, group->spareLinks );+        if( links )+        {+            group->linkCount += group->linkCount;+            group->linkBlocks = &links[0];+            group->spareLinks = &links[1];+        }+    }++    if( group->spareLinks )+    {+        result = PaUtil_AllocateMemory( size );+        if( result )+        {+            link = group->spareLinks;+            group->spareLinks = link->next;++            link->buffer = result;+            link->next = group->allocations;++            group->allocations = link;+        }+    }++    return result;    +}+++void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer )+{+    struct PaUtilAllocationGroupLink *current = group->allocations;+    struct PaUtilAllocationGroupLink *previous = 0;++    if( buffer == 0 )+        return;++    /* find the right link and remove it */+    while( current )+    {+        if( current->buffer == buffer )+        {+            if( previous )+            {+                previous->next = current->next;+            }+            else+            {+                group->allocations = current->next;+            }++            current->buffer = 0;+            current->next = group->spareLinks;+            group->spareLinks = current;++            break;+        }+        +        previous = current;+        current = current->next;+    }++    PaUtil_FreeMemory( buffer ); /* free the memory whether we found it in the list or not */+}+++void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group )+{+    struct PaUtilAllocationGroupLink *current = group->allocations;+    struct PaUtilAllocationGroupLink *previous = 0;++    /* free all buffers in the allocations list */+    while( current )+    {+        PaUtil_FreeMemory( current->buffer );+        current->buffer = 0;++        previous = current;+        current = current->next;+    }++    /* link the former allocations list onto the front of the spareLinks list */+    if( previous )+    {+        previous->next = group->spareLinks;+        group->spareLinks = group->allocations;+        group->allocations = 0;+    }+}+
+ portaudio/src/common/pa_converters.c view
@@ -0,0 +1,1983 @@+/*+ * $Id: pa_converters.c 1748 2011-09-01 22:08:32Z philburk $+ * Portable Audio I/O Library sample conversion mechanism+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Conversion function implementations.+ + If the C9x function lrintf() is available, define PA_USE_C99_LRINTF to use it++ @todo Consider whether functions which dither but don't clip should exist,+ V18 automatically enabled clipping whenever dithering was selected. Perhaps+ we should do the same. +    see: "require clipping for dithering sample conversion functions?"+    http://www.portaudio.com/trac/ticket/112++ @todo implement the converters marked IMPLEMENT ME: Int32_To_Int24_Dither,+ Int32_To_UInt8_Dither, Int24_To_Int16_Dither, Int24_To_Int8_Dither, + Int24_To_UInt8_Dither, Int16_To_Int8_Dither, Int16_To_UInt8_Dither+    see: "some conversion functions are not implemented in pa_converters.c"+    http://www.portaudio.com/trac/ticket/35++ @todo review the converters marked REVIEW: Float32_To_Int32,+ Float32_To_Int32_Dither, Float32_To_Int32_Clip, Float32_To_Int32_DitherClip,+ Int32_To_Int16_Dither, Int32_To_Int8_Dither, Int16_To_Int32+*/+++#include "pa_converters.h"+#include "pa_dither.h"+#include "pa_endianness.h"+#include "pa_types.h"+++PaSampleFormat PaUtil_SelectClosestAvailableFormat(+        PaSampleFormat availableFormats, PaSampleFormat format )+{+    PaSampleFormat result;++    format &= ~paNonInterleaved;+    availableFormats &= ~paNonInterleaved;+    +    if( (format & availableFormats) == 0 )+    {+        /* NOTE: this code depends on the sample format constants being in+            descending order of quality - ie best quality is 0+            FIXME: should write an assert which checks that all of the+            known constants conform to that requirement.+        */++        if( format != 0x01 )+        {+            /* scan for better formats */+            result = format;+            do+            {+                result >>= 1;+            }+            while( (result & availableFormats) == 0 && result != 0 );+        }+        else+        {+            result = 0;+        }+        +        if( result == 0 ){+            /* scan for worse formats */+            result = format;+            do+            {+                result <<= 1;+            }+            while( (result & availableFormats) == 0 && result != paCustomFormat );++            if( (result & availableFormats) == 0 )+                result = paSampleFormatNotSupported;+        }+        +    }else{+        result = format;+    }++    return result;+}++/* -------------------------------------------------------------------------- */++#define PA_SELECT_FORMAT_( format, float32, int32, int24, int16, int8, uint8 ) \+    switch( format & ~paNonInterleaved ){                                      \+    case paFloat32:                                                            \+        float32                                                                \+    case paInt32:                                                              \+        int32                                                                  \+    case paInt24:                                                              \+        int24                                                                  \+    case paInt16:                                                              \+        int16                                                                  \+    case paInt8:                                                               \+        int8                                                                   \+    case paUInt8:                                                              \+        uint8                                                                  \+    default: return 0;                                                         \+    }++/* -------------------------------------------------------------------------- */++#define PA_SELECT_CONVERTER_DITHER_CLIP_( flags, source, destination )         \+    if( flags & paClipOff ){ /* no clip */                                     \+        if( flags & paDitherOff ){ /* no dither */                             \+            return paConverters. source ## _To_ ## destination;                \+        }else{ /* dither */                                                    \+            return paConverters. source ## _To_ ## destination ## _Dither;     \+        }                                                                      \+    }else{ /* clip */                                                          \+        if( flags & paDitherOff ){ /* no dither */                             \+            return paConverters. source ## _To_ ## destination ## _Clip;       \+        }else{ /* dither */                                                    \+            return paConverters. source ## _To_ ## destination ## _DitherClip; \+        }                                                                      \+    }++/* -------------------------------------------------------------------------- */++#define PA_SELECT_CONVERTER_DITHER_( flags, source, destination )              \+    if( flags & paDitherOff ){ /* no dither */                                 \+        return paConverters. source ## _To_ ## destination;                    \+    }else{ /* dither */                                                        \+        return paConverters. source ## _To_ ## destination ## _Dither;         \+    }++/* -------------------------------------------------------------------------- */++#define PA_USE_CONVERTER_( source, destination )\+    return paConverters. source ## _To_ ## destination;++/* -------------------------------------------------------------------------- */++#define PA_UNITY_CONVERSION_( wordlength )\+    return paConverters. Copy_ ## wordlength ## _To_ ## wordlength;++/* -------------------------------------------------------------------------- */++PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat,+        PaSampleFormat destinationFormat, PaStreamFlags flags )+{+    PA_SELECT_FORMAT_( sourceFormat,+                       /* paFloat32: */+                       PA_SELECT_FORMAT_( destinationFormat,+                                          /* paFloat32: */        PA_UNITY_CONVERSION_( 32 ),+                                          /* paInt32: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int32 ),+                                          /* paInt24: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int24 ),+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int16 ),+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int8 ),+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, UInt8 )+                                        ),+                       /* paInt32: */+                       PA_SELECT_FORMAT_( destinationFormat,+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int32, Float32 ),+                                          /* paInt32: */          PA_UNITY_CONVERSION_( 32 ),+                                          /* paInt24: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int24 ),+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int16 ),+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int8 ),+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, UInt8 )+                                        ),+                       /* paInt24: */+                       PA_SELECT_FORMAT_( destinationFormat,+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int24, Float32 ),+                                          /* paInt32: */          PA_USE_CONVERTER_( Int24, Int32 ),+                                          /* paInt24: */          PA_UNITY_CONVERSION_( 24 ),+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int16 ),+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int8 ),+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int24, UInt8 )+                                        ),+                       /* paInt16: */+                       PA_SELECT_FORMAT_( destinationFormat,+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int16, Float32 ),+                                          /* paInt32: */          PA_USE_CONVERTER_( Int16, Int32 ),+                                          /* paInt24: */          PA_USE_CONVERTER_( Int16, Int24 ),+                                          /* paInt16: */          PA_UNITY_CONVERSION_( 16 ),+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int16, Int8 ),+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int16, UInt8 )+                                        ),+                       /* paInt8: */+                       PA_SELECT_FORMAT_( destinationFormat,+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int8, Float32 ),+                                          /* paInt32: */          PA_USE_CONVERTER_( Int8, Int32 ),+                                          /* paInt24: */          PA_USE_CONVERTER_( Int8, Int24 ),+                                          /* paInt16: */          PA_USE_CONVERTER_( Int8, Int16 ),+                                          /* paInt8: */           PA_UNITY_CONVERSION_( 8 ),+                                          /* paUInt8: */          PA_USE_CONVERTER_( Int8, UInt8 )+                                        ),+                       /* paUInt8: */+                       PA_SELECT_FORMAT_( destinationFormat,+                                          /* paFloat32: */        PA_USE_CONVERTER_( UInt8, Float32 ),+                                          /* paInt32: */          PA_USE_CONVERTER_( UInt8, Int32 ),+                                          /* paInt24: */          PA_USE_CONVERTER_( UInt8, Int24 ),+                                          /* paInt16: */          PA_USE_CONVERTER_( UInt8, Int16 ),+                                          /* paInt8: */           PA_USE_CONVERTER_( UInt8, Int8 ),+                                          /* paUInt8: */          PA_UNITY_CONVERSION_( 8 )+                                        )+                     )+}++/* -------------------------------------------------------------------------- */++#ifdef PA_NO_STANDARD_CONVERTERS++/* -------------------------------------------------------------------------- */++PaUtilConverterTable paConverters = {+    0, /* PaUtilConverter *Float32_To_Int32; */+    0, /* PaUtilConverter *Float32_To_Int32_Dither; */+    0, /* PaUtilConverter *Float32_To_Int32_Clip; */+    0, /* PaUtilConverter *Float32_To_Int32_DitherClip; */++    0, /* PaUtilConverter *Float32_To_Int24; */+    0, /* PaUtilConverter *Float32_To_Int24_Dither; */+    0, /* PaUtilConverter *Float32_To_Int24_Clip; */+    0, /* PaUtilConverter *Float32_To_Int24_DitherClip; */++    0, /* PaUtilConverter *Float32_To_Int16; */+    0, /* PaUtilConverter *Float32_To_Int16_Dither; */+    0, /* PaUtilConverter *Float32_To_Int16_Clip; */+    0, /* PaUtilConverter *Float32_To_Int16_DitherClip; */++    0, /* PaUtilConverter *Float32_To_Int8; */+    0, /* PaUtilConverter *Float32_To_Int8_Dither; */+    0, /* PaUtilConverter *Float32_To_Int8_Clip; */+    0, /* PaUtilConverter *Float32_To_Int8_DitherClip; */++    0, /* PaUtilConverter *Float32_To_UInt8; */+    0, /* PaUtilConverter *Float32_To_UInt8_Dither; */+    0, /* PaUtilConverter *Float32_To_UInt8_Clip; */+    0, /* PaUtilConverter *Float32_To_UInt8_DitherClip; */++    0, /* PaUtilConverter *Int32_To_Float32; */+    0, /* PaUtilConverter *Int32_To_Int24; */+    0, /* PaUtilConverter *Int32_To_Int24_Dither; */+    0, /* PaUtilConverter *Int32_To_Int16; */+    0, /* PaUtilConverter *Int32_To_Int16_Dither; */+    0, /* PaUtilConverter *Int32_To_Int8; */+    0, /* PaUtilConverter *Int32_To_Int8_Dither; */+    0, /* PaUtilConverter *Int32_To_UInt8; */+    0, /* PaUtilConverter *Int32_To_UInt8_Dither; */++    0, /* PaUtilConverter *Int24_To_Float32; */+    0, /* PaUtilConverter *Int24_To_Int32; */+    0, /* PaUtilConverter *Int24_To_Int16; */+    0, /* PaUtilConverter *Int24_To_Int16_Dither; */+    0, /* PaUtilConverter *Int24_To_Int8; */+    0, /* PaUtilConverter *Int24_To_Int8_Dither; */+    0, /* PaUtilConverter *Int24_To_UInt8; */+    0, /* PaUtilConverter *Int24_To_UInt8_Dither; */+    +    0, /* PaUtilConverter *Int16_To_Float32; */+    0, /* PaUtilConverter *Int16_To_Int32; */+    0, /* PaUtilConverter *Int16_To_Int24; */+    0, /* PaUtilConverter *Int16_To_Int8; */+    0, /* PaUtilConverter *Int16_To_Int8_Dither; */+    0, /* PaUtilConverter *Int16_To_UInt8; */+    0, /* PaUtilConverter *Int16_To_UInt8_Dither; */++    0, /* PaUtilConverter *Int8_To_Float32; */+    0, /* PaUtilConverter *Int8_To_Int32; */+    0, /* PaUtilConverter *Int8_To_Int24 */+    0, /* PaUtilConverter *Int8_To_Int16; */+    0, /* PaUtilConverter *Int8_To_UInt8; */++    0, /* PaUtilConverter *UInt8_To_Float32; */+    0, /* PaUtilConverter *UInt8_To_Int32; */+    0, /* PaUtilConverter *UInt8_To_Int24; */+    0, /* PaUtilConverter *UInt8_To_Int16; */+    0, /* PaUtilConverter *UInt8_To_Int8; */++    0, /* PaUtilConverter *Copy_8_To_8; */+    0, /* PaUtilConverter *Copy_16_To_16; */+    0, /* PaUtilConverter *Copy_24_To_24; */+    0  /* PaUtilConverter *Copy_32_To_32; */+};++/* -------------------------------------------------------------------------- */++#else /* PA_NO_STANDARD_CONVERTERS is not defined */++/* -------------------------------------------------------------------------- */++#define PA_CLIP_( val, min, max )\+    { val = ((val) < (min)) ? (min) : (((val) > (max)) ? (max) : (val)); }+++static const float const_1_div_128_ = 1.0f / 128.0f;  /* 8 bit multiplier */++static const float const_1_div_32768_ = 1.0f / 32768.f; /* 16 bit multiplier */++static const double const_1_div_2147483648_ = 1.0 / 2147483648.0; /* 32 bit multiplier */++/* -------------------------------------------------------------------------- */++static void Float32_To_Int32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt32 *dest =  (PaInt32*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        /* REVIEW */+#ifdef PA_USE_C99_LRINTF+        float scaled = *src * 0x7FFFFFFF;+        *dest = lrintf(scaled-0.5f);+#else+        double scaled = *src * 0x7FFFFFFF;+        *dest = (PaInt32) scaled;        +#endif+        +        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int32_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt32 *dest =  (PaInt32*)destinationBuffer;++    while( count-- )+    {+        /* REVIEW */+#ifdef PA_USE_C99_LRINTF+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = ((float)*src * (2147483646.0f)) + dither;+        *dest = lrintf(dithered - 0.5f);+#else+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        double dithered = ((double)*src * (2147483646.0)) + dither;+        *dest = (PaInt32) dithered;+#endif+        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int32_Clip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt32 *dest =  (PaInt32*)destinationBuffer;+    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {+        /* REVIEW */+#ifdef PA_USE_C99_LRINTF+        float scaled = *src * 0x7FFFFFFF;+        PA_CLIP_( scaled, -2147483648.f, 2147483647.f  );+        *dest = lrintf(scaled-0.5f);+#else+        double scaled = *src * 0x7FFFFFFF;+        PA_CLIP_( scaled, -2147483648., 2147483647.  );+        *dest = (PaInt32) scaled;+#endif++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int32_DitherClip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt32 *dest =  (PaInt32*)destinationBuffer;++    while( count-- )+    {+        /* REVIEW */+#ifdef PA_USE_C99_LRINTF+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = ((float)*src * (2147483646.0f)) + dither;+        PA_CLIP_( dithered, -2147483648.f, 2147483647.f  );+        *dest = lrintf(dithered-0.5f);+#else+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        double dithered = ((double)*src * (2147483646.0)) + dither;+        PA_CLIP_( dithered, -2147483648., 2147483647.  );+        *dest = (PaInt32) dithered;+#endif++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int24(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    PaInt32 temp;++    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {+        /* convert to 32 bit and drop the low 8 bits */+        double scaled = (double)(*src) * 2147483647.0;+        temp = (PaInt32) scaled;+        +#if defined(PA_LITTLE_ENDIAN)+        dest[0] = (unsigned char)(temp >> 8);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 24);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (unsigned char)(temp >> 24);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 8);+#endif++        src += sourceStride;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int24_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    PaInt32 temp;++    while( count-- )+    {+        /* convert to 32 bit and drop the low 8 bits */++        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        double dithered = ((double)*src * (2147483646.0)) + dither;+        +        temp = (PaInt32) dithered;++#if defined(PA_LITTLE_ENDIAN)+        dest[0] = (unsigned char)(temp >> 8);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 24);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (unsigned char)(temp >> 24);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 8);+#endif++        src += sourceStride;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int24_Clip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    PaInt32 temp;++    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {+        /* convert to 32 bit and drop the low 8 bits */+        double scaled = *src * 0x7FFFFFFF;+        PA_CLIP_( scaled, -2147483648., 2147483647.  );+        temp = (PaInt32) scaled;++#if defined(PA_LITTLE_ENDIAN)+        dest[0] = (unsigned char)(temp >> 8);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 24);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (unsigned char)(temp >> 24);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 8);+#endif++        src += sourceStride;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int24_DitherClip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    PaInt32 temp;+    +    while( count-- )+    {+        /* convert to 32 bit and drop the low 8 bits */+        +        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        double dithered = ((double)*src * (2147483646.0)) + dither;+        PA_CLIP_( dithered, -2147483648., 2147483647.  );+        +        temp = (PaInt32) dithered;++#if defined(PA_LITTLE_ENDIAN)+        dest[0] = (unsigned char)(temp >> 8);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 24);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (unsigned char)(temp >> 24);+        dest[1] = (unsigned char)(temp >> 16);+        dest[2] = (unsigned char)(temp >> 8);+#endif++        src += sourceStride;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int16(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt16 *dest =  (PaInt16*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+#ifdef PA_USE_C99_LRINTF+        float tempf = (*src * (32767.0f)) ;+        *dest = lrintf(tempf-0.5f);+#else+        short samp = (short) (*src * (32767.0f));+        *dest = samp;+#endif++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int16_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt16 *dest = (PaInt16*)destinationBuffer;++    while( count-- )+    {++        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = (*src * (32766.0f)) + dither;++#ifdef PA_USE_C99_LRINTF+        *dest = lrintf(dithered-0.5f);+#else+        *dest = (PaInt16) dithered;+#endif++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int16_Clip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt16 *dest =  (PaInt16*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+#ifdef PA_USE_C99_LRINTF+        long samp = lrintf((*src * (32767.0f)) -0.5f);+#else+        long samp = (PaInt32) (*src * (32767.0f));+#endif+        PA_CLIP_( samp, -0x8000, 0x7FFF );+        *dest = (PaInt16) samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int16_DitherClip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    PaInt16 *dest =  (PaInt16*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {++        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = (*src * (32766.0f)) + dither;+        PaInt32 samp = (PaInt32) dithered;+        PA_CLIP_( samp, -0x8000, 0x7FFF );+#ifdef PA_USE_C99_LRINTF+        *dest = lrintf(samp-0.5f);+#else+        *dest = (PaInt16) samp;+#endif++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        signed char samp = (signed char) (*src * (127.0f));+        *dest = samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    +    while( count-- )+    {+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = (*src * (126.0f)) + dither;+        PaInt32 samp = (PaInt32) dithered;+        *dest = (signed char) samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int8_Clip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        PaInt32 samp = (PaInt32)(*src * (127.0f));+        PA_CLIP_( samp, -0x80, 0x7F );+        *dest = (signed char) samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_Int8_DitherClip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = (*src * (126.0f)) + dither;+        PaInt32 samp = (PaInt32) dithered;+        PA_CLIP_( samp, -0x80, 0x7F );+        *dest = (signed char) samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_UInt8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        unsigned char samp = (unsigned char)(128 + ((unsigned char) (*src * (127.0f))));+        *dest = samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_UInt8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    +    while( count-- )+    {+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = (*src * (126.0f)) + dither;+        PaInt32 samp = (PaInt32) dithered;+        *dest = (unsigned char) (128 + samp);+        +        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_UInt8_Clip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        PaInt32 samp = 128 + (PaInt32)(*src * (127.0f));+        PA_CLIP_( samp, 0x0000, 0x00FF );+        *dest = (unsigned char) samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Float32_To_UInt8_DitherClip(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    float *src = (float*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );+        /* use smaller scaler to prevent overflow when we add the dither */+        float dithered = (*src * (126.0f)) + dither;+        PaInt32 samp = 128 + (PaInt32) dithered;+        PA_CLIP_( samp, 0x0000, 0x00FF );+        *dest = (unsigned char) samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_Float32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src = (PaInt32*)sourceBuffer;+    float *dest =  (float*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        *dest = (float) ((double)*src * const_1_div_2147483648_);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_Int24(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src    = (PaInt32*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    (void) ditherGenerator; /* unused parameter */+    +	while( count-- )+    {+		/* REVIEW */+#if defined(PA_LITTLE_ENDIAN)+        dest[0] = (unsigned char)(*src >> 8);+        dest[1] = (unsigned char)(*src >> 16);+        dest[2] = (unsigned char)(*src >> 24);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (unsigned char)(*src >> 24);+        dest[1] = (unsigned char)(*src >> 16);+        dest[2] = (unsigned char)(*src >> 8);+#endif+        src += sourceStride;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_Int24_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    (void) destinationBuffer; /* unused parameters */+    (void) destinationStride; /* unused parameters */+    (void) sourceBuffer; /* unused parameters */+    (void) sourceStride; /* unused parameters */+    (void) count; /* unused parameters */+    (void) ditherGenerator; /* unused parameters */+    /* IMPLEMENT ME */+}++/* -------------------------------------------------------------------------- */++static void Int32_To_Int16(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src = (PaInt32*)sourceBuffer;+    PaInt16 *dest =  (PaInt16*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        *dest = (PaInt16) ((*src) >> 16);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_Int16_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src = (PaInt32*)sourceBuffer;+    PaInt16 *dest =  (PaInt16*)destinationBuffer;+    PaInt32 dither;++    while( count-- )+    {+        /* REVIEW */+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );+        *dest = (PaInt16) ((((*src)>>1) + dither) >> 15);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_Int8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src = (PaInt32*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        *dest = (signed char) ((*src) >> 24);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_Int8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src = (PaInt32*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    PaInt32 dither;++    while( count-- )+    {+        /* REVIEW */+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );+        *dest = (signed char) ((((*src)>>1) + dither) >> 23);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_UInt8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src = (PaInt32*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+		(*dest) = (unsigned char)(((*src) >> 24) + 128); ++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int32_To_UInt8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt32 *src = (PaInt32*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        /* IMPLEMENT ME */++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_Float32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    float *dest = (float*)destinationBuffer;+    PaInt32 temp;++    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {++#if defined(PA_LITTLE_ENDIAN)+        temp = (((PaInt32)src[0]) << 8);  +        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 24);+#elif defined(PA_BIG_ENDIAN)+        temp = (((PaInt32)src[0]) << 24);+        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 8);+#endif++        *dest = (float) ((double)temp * const_1_div_2147483648_);++        src += sourceStride * 3;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_Int32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src  = (unsigned char*)sourceBuffer;+    PaInt32 *dest = (PaInt32*)  destinationBuffer;+    PaInt32 temp;++    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {++#if defined(PA_LITTLE_ENDIAN)+        temp = (((PaInt32)src[0]) << 8);  +        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 24);+#elif defined(PA_BIG_ENDIAN)+        temp = (((PaInt32)src[0]) << 24);+        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 8);+#endif++        *dest = temp;++        src += sourceStride * 3;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_Int16(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    PaInt16 *dest = (PaInt16*)destinationBuffer;+    +    PaInt16 temp;++    (void) ditherGenerator; /* unused parameter */+        +    while( count-- )+    {+		+#if defined(PA_LITTLE_ENDIAN)+		/* src[0] is discarded */+        temp = (((PaInt16)src[1]));+        temp = temp | (PaInt16)(((PaInt16)src[2]) << 8);+#elif defined(PA_BIG_ENDIAN)+		/* src[2] is discarded */+        temp = (PaInt16)(((PaInt16)src[0]) << 8);+        temp = temp | (((PaInt16)src[1]));+#endif++        *dest = temp;++        src += sourceStride * 3;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_Int16_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    PaInt16 *dest = (PaInt16*)destinationBuffer;++    PaInt32 temp, dither;++    while( count-- )+    {++#if defined(PA_LITTLE_ENDIAN)+        temp = (((PaInt32)src[0]) << 8);  +        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 24);+#elif defined(PA_BIG_ENDIAN)+        temp = (((PaInt32)src[0]) << 24);+        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 8);+#endif++        /* REVIEW */+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );+        *dest = (PaInt16) (((temp >> 1) + dither) >> 15);++        src  += sourceStride * 3;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_Int8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    signed char  *dest = (signed char*)destinationBuffer;+    +    (void) ditherGenerator; /* unused parameter */+        +    while( count-- )+    {	+	+#if defined(PA_LITTLE_ENDIAN)+		/* src[0] is discarded */+		/* src[1] is discarded */+        *dest = src[2];+#elif defined(PA_BIG_ENDIAN)+		/* src[2] is discarded */+		/* src[1] is discarded */+		*dest = src[0];+#endif++        src += sourceStride * 3;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_Int8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    signed char  *dest = (signed char*)destinationBuffer;+    +    PaInt32 temp, dither;++    while( count-- )+    {++#if defined(PA_LITTLE_ENDIAN)+        temp = (((PaInt32)src[0]) << 8);  +        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 24);+#elif defined(PA_BIG_ENDIAN)+        temp = (((PaInt32)src[0]) << 24);+        temp = temp | (((PaInt32)src[1]) << 16);+        temp = temp | (((PaInt32)src[2]) << 8);+#endif++        /* REVIEW */+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );+        *dest = (signed char) (((temp >> 1) + dither) >> 23);++        src += sourceStride * 3;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_UInt8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    +    (void) ditherGenerator; /* unused parameter */+        +    while( count-- )+    {+		+#if defined(PA_LITTLE_ENDIAN)+		/* src[0] is discarded */+		/* src[1] is discarded */+        *dest = (unsigned char)(src[2] + 128);+#elif defined(PA_BIG_ENDIAN)+        *dest = (unsigned char)(src[0] + 128);+		/* src[1] is discarded */+		/* src[2] is discarded */		+#endif++        src += sourceStride * 3;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int24_To_UInt8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    (void) destinationBuffer; /* unused parameters */+    (void) destinationStride; /* unused parameters */+    (void) sourceBuffer; /* unused parameters */+    (void) sourceStride; /* unused parameters */+    (void) count; /* unused parameters */+    (void) ditherGenerator; /* unused parameters */+    /* IMPLEMENT ME */+}++/* -------------------------------------------------------------------------- */++static void Int16_To_Float32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt16 *src = (PaInt16*)sourceBuffer;+    float *dest =  (float*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        float samp = *src * const_1_div_32768_; /* FIXME: i'm concerned about this being asymetrical with float->int16 -rb */+        *dest = samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int16_To_Int32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt16 *src = (PaInt16*)sourceBuffer;+    PaInt32 *dest =  (PaInt32*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        /* REVIEW: we should consider something like+            (*src << 16) | (*src & 0xFFFF)+        */+        +        *dest = *src << 16;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int16_To_Int24(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt16 *src   = (PaInt16*) sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    PaInt16 temp;++    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {+        temp = *src;+        +#if defined(PA_LITTLE_ENDIAN)+        dest[0] = 0;+        dest[1] = (unsigned char)(temp);+        dest[2] = (unsigned char)(temp >> 8);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (unsigned char)(temp >> 8);+        dest[1] = (unsigned char)(temp);+        dest[2] = 0;+#endif++        src += sourceStride;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Int16_To_Int8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt16 *src = (PaInt16*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        (*dest) = (signed char)((*src) >> 8);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int16_To_Int8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt16 *src = (PaInt16*)sourceBuffer;+    signed char *dest =  (signed char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        /* IMPLEMENT ME */++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int16_To_UInt8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt16 *src = (PaInt16*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+		(*dest) = (unsigned char)(((*src) >> 8) + 128); ++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int16_To_UInt8_Dither(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaInt16 *src = (PaInt16*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        /* IMPLEMENT ME */++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int8_To_Float32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    signed char *src = (signed char*)sourceBuffer;+    float *dest =  (float*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        float samp = *src * const_1_div_128_;+        *dest = samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int8_To_Int32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    signed char *src = (signed char*)sourceBuffer;+    PaInt32 *dest =  (PaInt32*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+		(*dest) = (*src) << 24;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int8_To_Int24(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    signed char *src = (signed char*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {++#if defined(PA_LITTLE_ENDIAN)+        dest[0] = 0;+        dest[1] = 0;+        dest[2] = (*src);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (*src);+        dest[1] = 0;+        dest[2] = 0;+#endif++        src += sourceStride;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Int8_To_Int16(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    signed char *src = (signed char*)sourceBuffer;+    PaInt16 *dest =  (PaInt16*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        (*dest) = (PaInt16)((*src) << 8);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Int8_To_UInt8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    signed char *src = (signed char*)sourceBuffer;+    unsigned char *dest =  (unsigned char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        (*dest) = (unsigned char)(*src + 128);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void UInt8_To_Float32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    float *dest =  (float*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        float samp = (*src - 128) * const_1_div_128_;+        *dest = samp;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void UInt8_To_Int32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    PaInt32 *dest = (PaInt32*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+		(*dest) = (*src - 128) << 24;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void UInt8_To_Int24(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+	unsigned char *src  = (unsigned char*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+    (void) ditherGenerator; /* unused parameters */+    +	while( count-- )+    {++#if defined(PA_LITTLE_ENDIAN)+        dest[0] = 0;+        dest[1] = 0;+        dest[2] = (unsigned char)(*src - 128);+#elif defined(PA_BIG_ENDIAN)+        dest[0] = (unsigned char)(*src - 128);+        dest[1] = 0;+        dest[2] = 0;+#endif+		+        src += sourceStride;+        dest += destinationStride * 3;    +	}+}++/* -------------------------------------------------------------------------- */++static void UInt8_To_Int16(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    PaInt16 *dest =  (PaInt16*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        (*dest) = (PaInt16)((*src - 128) << 8);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void UInt8_To_Int8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    signed char  *dest = (signed char*)destinationBuffer;+    (void)ditherGenerator; /* unused parameter */++    while( count-- )+    {+        (*dest) = (signed char)(*src - 128);++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Copy_8_To_8(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;+                                                      +    (void) ditherGenerator; /* unused parameter */++    while( count-- )+    {+        *dest = *src;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Copy_16_To_16(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaUint16 *src = (PaUint16 *)sourceBuffer;+    PaUint16 *dest = (PaUint16 *)destinationBuffer;+                                                        +    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {+        *dest = *src;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Copy_24_To_24(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    unsigned char *src = (unsigned char*)sourceBuffer;+    unsigned char *dest = (unsigned char*)destinationBuffer;++    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {+        dest[0] = src[0];+        dest[1] = src[1];+        dest[2] = src[2];++        src += sourceStride * 3;+        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Copy_32_To_32(+    void *destinationBuffer, signed int destinationStride,+    void *sourceBuffer, signed int sourceStride,+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )+{+    PaUint32 *dest = (PaUint32 *)destinationBuffer;+    PaUint32 *src = (PaUint32 *)sourceBuffer;++    (void) ditherGenerator; /* unused parameter */+    +    while( count-- )+    {+        *dest = *src;++        src += sourceStride;+        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++PaUtilConverterTable paConverters = {+    Float32_To_Int32,              /* PaUtilConverter *Float32_To_Int32; */+    Float32_To_Int32_Dither,       /* PaUtilConverter *Float32_To_Int32_Dither; */+    Float32_To_Int32_Clip,         /* PaUtilConverter *Float32_To_Int32_Clip; */+    Float32_To_Int32_DitherClip,   /* PaUtilConverter *Float32_To_Int32_DitherClip; */++    Float32_To_Int24,              /* PaUtilConverter *Float32_To_Int24; */+    Float32_To_Int24_Dither,       /* PaUtilConverter *Float32_To_Int24_Dither; */+    Float32_To_Int24_Clip,         /* PaUtilConverter *Float32_To_Int24_Clip; */+    Float32_To_Int24_DitherClip,   /* PaUtilConverter *Float32_To_Int24_DitherClip; */+    +    Float32_To_Int16,              /* PaUtilConverter *Float32_To_Int16; */+    Float32_To_Int16_Dither,       /* PaUtilConverter *Float32_To_Int16_Dither; */+    Float32_To_Int16_Clip,         /* PaUtilConverter *Float32_To_Int16_Clip; */+    Float32_To_Int16_DitherClip,   /* PaUtilConverter *Float32_To_Int16_DitherClip; */++    Float32_To_Int8,               /* PaUtilConverter *Float32_To_Int8; */+    Float32_To_Int8_Dither,        /* PaUtilConverter *Float32_To_Int8_Dither; */+    Float32_To_Int8_Clip,          /* PaUtilConverter *Float32_To_Int8_Clip; */+    Float32_To_Int8_DitherClip,    /* PaUtilConverter *Float32_To_Int8_DitherClip; */++    Float32_To_UInt8,              /* PaUtilConverter *Float32_To_UInt8; */+    Float32_To_UInt8_Dither,       /* PaUtilConverter *Float32_To_UInt8_Dither; */+    Float32_To_UInt8_Clip,         /* PaUtilConverter *Float32_To_UInt8_Clip; */+    Float32_To_UInt8_DitherClip,   /* PaUtilConverter *Float32_To_UInt8_DitherClip; */++    Int32_To_Float32,              /* PaUtilConverter *Int32_To_Float32; */+    Int32_To_Int24,                /* PaUtilConverter *Int32_To_Int24; */+    Int32_To_Int24_Dither,         /* PaUtilConverter *Int32_To_Int24_Dither; */+    Int32_To_Int16,                /* PaUtilConverter *Int32_To_Int16; */+    Int32_To_Int16_Dither,         /* PaUtilConverter *Int32_To_Int16_Dither; */+    Int32_To_Int8,                 /* PaUtilConverter *Int32_To_Int8; */+    Int32_To_Int8_Dither,          /* PaUtilConverter *Int32_To_Int8_Dither; */+    Int32_To_UInt8,                /* PaUtilConverter *Int32_To_UInt8; */+    Int32_To_UInt8_Dither,         /* PaUtilConverter *Int32_To_UInt8_Dither; */++    Int24_To_Float32,              /* PaUtilConverter *Int24_To_Float32; */+    Int24_To_Int32,                /* PaUtilConverter *Int24_To_Int32; */+    Int24_To_Int16,                /* PaUtilConverter *Int24_To_Int16; */+    Int24_To_Int16_Dither,         /* PaUtilConverter *Int24_To_Int16_Dither; */+    Int24_To_Int8,                 /* PaUtilConverter *Int24_To_Int8; */+    Int24_To_Int8_Dither,          /* PaUtilConverter *Int24_To_Int8_Dither; */+    Int24_To_UInt8,                /* PaUtilConverter *Int24_To_UInt8; */+    Int24_To_UInt8_Dither,         /* PaUtilConverter *Int24_To_UInt8_Dither; */++    Int16_To_Float32,              /* PaUtilConverter *Int16_To_Float32; */+    Int16_To_Int32,                /* PaUtilConverter *Int16_To_Int32; */+    Int16_To_Int24,                /* PaUtilConverter *Int16_To_Int24; */+    Int16_To_Int8,                 /* PaUtilConverter *Int16_To_Int8; */+    Int16_To_Int8_Dither,          /* PaUtilConverter *Int16_To_Int8_Dither; */+    Int16_To_UInt8,                /* PaUtilConverter *Int16_To_UInt8; */+    Int16_To_UInt8_Dither,         /* PaUtilConverter *Int16_To_UInt8_Dither; */++    Int8_To_Float32,               /* PaUtilConverter *Int8_To_Float32; */+    Int8_To_Int32,                 /* PaUtilConverter *Int8_To_Int32; */+    Int8_To_Int24,                 /* PaUtilConverter *Int8_To_Int24 */+    Int8_To_Int16,                 /* PaUtilConverter *Int8_To_Int16; */+    Int8_To_UInt8,                 /* PaUtilConverter *Int8_To_UInt8; */++    UInt8_To_Float32,              /* PaUtilConverter *UInt8_To_Float32; */+    UInt8_To_Int32,                /* PaUtilConverter *UInt8_To_Int32; */+    UInt8_To_Int24,                /* PaUtilConverter *UInt8_To_Int24; */+    UInt8_To_Int16,                /* PaUtilConverter *UInt8_To_Int16; */+    UInt8_To_Int8,                 /* PaUtilConverter *UInt8_To_Int8; */++    Copy_8_To_8,                   /* PaUtilConverter *Copy_8_To_8; */+    Copy_16_To_16,                 /* PaUtilConverter *Copy_16_To_16; */+    Copy_24_To_24,                 /* PaUtilConverter *Copy_24_To_24; */+    Copy_32_To_32                  /* PaUtilConverter *Copy_32_To_32; */+};++/* -------------------------------------------------------------------------- */++#endif /* PA_NO_STANDARD_CONVERTERS */++/* -------------------------------------------------------------------------- */++PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat )+{+    switch( destinationFormat & ~paNonInterleaved ){+    case paFloat32:+        return paZeroers.Zero32;+    case paInt32:+        return paZeroers.Zero32;+    case paInt24:+        return paZeroers.Zero24;+    case paInt16:+        return paZeroers.Zero16;+    case paInt8:+        return paZeroers.Zero8;+    case paUInt8:+        return paZeroers.ZeroU8;+    default: return 0;+    }+}++/* -------------------------------------------------------------------------- */++#ifdef PA_NO_STANDARD_ZEROERS++/* -------------------------------------------------------------------------- */++PaUtilZeroerTable paZeroers = {+    0,  /* PaUtilZeroer *ZeroU8; */+    0,  /* PaUtilZeroer *Zero8; */+    0,  /* PaUtilZeroer *Zero16; */+    0,  /* PaUtilZeroer *Zero24; */+    0,  /* PaUtilZeroer *Zero32; */+};++/* -------------------------------------------------------------------------- */++#else /* PA_NO_STANDARD_ZEROERS is not defined */++/* -------------------------------------------------------------------------- */++static void ZeroU8( void *destinationBuffer, signed int destinationStride,+        unsigned int count )+{+    unsigned char *dest = (unsigned char*)destinationBuffer;++    while( count-- )+    {+        *dest = 128;++        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Zero8( void *destinationBuffer, signed int destinationStride,+        unsigned int count )+{+    unsigned char *dest = (unsigned char*)destinationBuffer;++    while( count-- )+    {+        *dest = 0;++        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Zero16( void *destinationBuffer, signed int destinationStride,+        unsigned int count )+{+    PaUint16 *dest = (PaUint16 *)destinationBuffer;++    while( count-- )+    {+        *dest = 0;++        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++static void Zero24( void *destinationBuffer, signed int destinationStride,+        unsigned int count )+{+    unsigned char *dest = (unsigned char*)destinationBuffer;++    while( count-- )+    {+        dest[0] = 0;+        dest[1] = 0;+        dest[2] = 0;++        dest += destinationStride * 3;+    }+}++/* -------------------------------------------------------------------------- */++static void Zero32( void *destinationBuffer, signed int destinationStride,+        unsigned int count )+{+    PaUint32 *dest = (PaUint32 *)destinationBuffer;++    while( count-- )+    {+        *dest = 0;++        dest += destinationStride;+    }+}++/* -------------------------------------------------------------------------- */++PaUtilZeroerTable paZeroers = {+    ZeroU8,  /* PaUtilZeroer *ZeroU8; */+    Zero8,  /* PaUtilZeroer *Zero8; */+    Zero16,  /* PaUtilZeroer *Zero16; */+    Zero24,  /* PaUtilZeroer *Zero24; */+    Zero32,  /* PaUtilZeroer *Zero32; */+};++/* -------------------------------------------------------------------------- */++#endif /* PA_NO_STANDARD_ZEROERS */
+ portaudio/src/common/pa_cpuload.c view
@@ -0,0 +1,105 @@+/*+ * $Id: pa_cpuload.c 1577 2011-02-01 13:03:45Z rossb $+ * Portable Audio I/O Library CPU Load measurement functions+ * Portable CPU load measurement facility.+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 2002 Ross Bencina+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Functions to assist in measuring the CPU utilization of a callback+ stream. Used to implement the Pa_GetStreamCpuLoad() function.++ @todo Dynamically calculate the coefficients used to smooth the CPU Load+ Measurements over time to provide a uniform characterisation of CPU Load+ independent of rate at which PaUtil_BeginCpuLoadMeasurement /+ PaUtil_EndCpuLoadMeasurement are called. see http://www.portaudio.com/trac/ticket/113+*/+++#include "pa_cpuload.h"++#include <assert.h>++#include "pa_util.h"   /* for PaUtil_GetTime() */+++void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate )+{+    assert( sampleRate > 0 );++    measurer->samplingPeriod = 1. / sampleRate;+    measurer->averageLoad = 0.;+}++void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer )+{+    measurer->averageLoad = 0.;+}++void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer )+{+    measurer->measurementStartTime = PaUtil_GetTime();+}+++void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed )+{+    double measurementEndTime, secondsFor100Percent, measuredLoad;++    if( framesProcessed > 0 ){+        measurementEndTime = PaUtil_GetTime();++        assert( framesProcessed > 0 );+        secondsFor100Percent = framesProcessed * measurer->samplingPeriod;++        measuredLoad = (measurementEndTime - measurer->measurementStartTime) / secondsFor100Percent;++        /* Low pass filter the calculated CPU load to reduce jitter using a simple IIR low pass filter. */+        /** FIXME @todo these coefficients shouldn't be hardwired see: http://www.portaudio.com/trac/ticket/113 */+#define LOWPASS_COEFFICIENT_0   (0.9)+#define LOWPASS_COEFFICIENT_1   (0.99999 - LOWPASS_COEFFICIENT_0)++        measurer->averageLoad = (LOWPASS_COEFFICIENT_0 * measurer->averageLoad) ++                               (LOWPASS_COEFFICIENT_1 * measuredLoad);+    }+}+++double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer )+{+    return measurer->averageLoad;+}
+ portaudio/src/common/pa_debugprint.c view
@@ -0,0 +1,123 @@+/*
+ * $Id: pa_log.c $
+ * Portable Audio I/O Library Multi-Host API front end
+ * Validate function parameters and manage multiple host APIs.
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup common_src
+
+ @brief Implements log function.
+
+    PaUtil_SetLogPrintFunction can be user called to replace the provided
+	DefaultLogPrint function, which writes to stderr.
+	One can NOT pass var_args across compiler/dll boundaries as it is not
+	"byte code/abi portable". So the technique used here is to allocate a local
+	a static array, write in it, then callback the user with a pointer to its
+	start.
+*/
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#include "pa_debugprint.h"
+
+// for OutputDebugStringA
+#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
+	#define WIN32_LEAN_AND_MEAN // exclude rare headers
+	#include "windows.h"
+#endif
+
+// User callback
+static PaUtilLogCallback userCB = NULL;
+
+// Sets user callback
+void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb)
+{
+    userCB = cb;
+}
+
+/*
+ If your platform doesn’t have vsnprintf, you are stuck with a
+ VERY dangerous alternative, vsprintf (with no n)
+*/
+#if _MSC_VER
+	/* Some Windows Mobile SDKs don't define vsnprintf but all define _vsnprintf (hopefully).
+	   According to MSDN "vsnprintf is identical to _vsnprintf". So we use _vsnprintf with MSC.
+	*/
+	#define VSNPRINTF  _vsnprintf 
+#else
+	#define VSNPRINTF  vsnprintf
+#endif
+
+#define PA_LOG_BUF_SIZE 2048
+
+void PaUtil_DebugPrint( const char *format, ... )
+{
+	// Optional logging into Output console of Visual Studio
+#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
+	{
+		char buf[PA_LOG_BUF_SIZE];
+		va_list ap;
+		va_start(ap, format);
+		VSNPRINTF(buf, sizeof(buf), format, ap);
+		buf[sizeof(buf)-1] = 0;
+		OutputDebugStringA(buf);
+		va_end(ap);
+	}
+#endif
+
+	// Output to User-Callback
+    if (userCB != NULL)
+    {
+        char strdump[PA_LOG_BUF_SIZE];
+        va_list ap;
+        va_start(ap, format);
+        VSNPRINTF(strdump, sizeof(strdump), format, ap);
+        strdump[sizeof(strdump)-1] = 0;
+        userCB(strdump);
+        va_end(ap);
+    }
+    else
+	// Standard output to stderr
+    {
+        va_list ap;
+        va_start(ap, format);
+        vfprintf(stderr, format, ap);
+        va_end(ap);
+        fflush(stderr);
+    }
+}
+ portaudio/src/common/pa_dither.c view
@@ -0,0 +1,218 @@+/*+ * $Id: pa_dither.c 1418 2009-10-12 21:00:53Z philburk $+ * Portable Audio I/O Library triangular dither generator+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Functions for generating dither noise+*/++#include "pa_types.h"+#include "pa_dither.h"+++/* Note that the linear congruential algorithm requires 32 bit integers+ * because it uses arithmetic overflow. So use PaUint32 instead of+ * unsigned long so it will work on 64 bit systems.+ */++#define PA_DITHER_BITS_   (15)+++void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *state )+{+    state->previous = 0;+    state->randSeed1 = 22222;+    state->randSeed2 = 5555555;+}+++PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state )+{+    PaInt32 current, highPass;++    /* Generate two random numbers. */+    state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;+    state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;++    /* Generate triangular distribution about 0.+     * Shift before adding to prevent overflow which would skew the distribution.+     * Also shift an extra bit for the high pass filter. +     */+#define DITHER_SHIFT_  ((sizeof(PaInt32)*8 - PA_DITHER_BITS_) + 1)+	+    current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) ++              (((PaInt32)state->randSeed2)>>DITHER_SHIFT_);++    /* High pass filter to reduce audibility. */+    highPass = current - state->previous;+    state->previous = current;+    return highPass;+}+++/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */+#define PA_FLOAT_DITHER_SCALE_  (1.0f / ((1<<PA_DITHER_BITS_)-1))+static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;++float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *state )+{+    PaInt32 current, highPass;++    /* Generate two random numbers. */+    state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;+    state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;++    /* Generate triangular distribution about 0.+     * Shift before adding to prevent overflow which would skew the distribution.+     * Also shift an extra bit for the high pass filter. +     */+    current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) ++              (((PaInt32)state->randSeed2)>>DITHER_SHIFT_);++    /* High pass filter to reduce audibility. */+    highPass = current - state->previous;+    state->previous = current;+    return ((float)highPass) * const_float_dither_scale_;+}+++/*+The following alternate dither algorithms (from musicdsp.org) could be+considered+*/++/*Noise shaped dither  (March 2000)+-------------------++This is a simple implementation of highpass triangular-PDF dither with+2nd-order noise shaping, for use when truncating floating point audio+data to fixed point.++The noise shaping lowers the noise floor by 11dB below 5kHz (@ 44100Hz+sample rate) compared to triangular-PDF dither. The code below assumes+input data is in the range +1 to -1 and doesn't check for overloads!++To save time when generating dither for multiple channels you can do+things like this:  r3=(r1 & 0x7F)<<8; instead of calling rand() again.++++  int   r1, r2;                //rectangular-PDF random numbers+  float s1, s2;                //error feedback buffers+  float s = 0.5f;              //set to 0.0f for no noise shaping+  float w = pow(2.0,bits-1);   //word length (usually bits=16)+  float wi= 1.0f/w;            +  float d = wi / RAND_MAX;     //dither amplitude (2 lsb)+  float o = wi * 0.5f;         //remove dc offset+  float in, tmp;+  int   out;+++//for each sample...++  r2=r1;                               //can make HP-TRI dither by+  r1=rand();                           //subtracting previous rand()+    +  in += s * (s1 + s1 - s2);            //error feedback+  tmp = in + o + d * (float)(r1 - r2); //dc offset and dither +  +  out = (int)(w * tmp);                //truncate downwards+  if(tmp<0.0f) out--;                  //this is faster than floor()++  s2 = s1;                            +  s1 = in - wi * (float)out;           //error++++-- +paul.kellett@maxim.abel.co.uk+http://www.maxim.abel.co.uk+*/+++/*+16-to-8-bit first-order dither++Type : First order error feedforward dithering code+References : Posted by Jon Watte++Notes : +This is about as simple a dithering algorithm as you can implement, but it's+likely to sound better than just truncating to N bits.++Note that you might not want to carry forward the full difference for infinity.+It's probably likely that the worst performance hit comes from the saturation+conditionals, which can be avoided with appropriate instructions on many DSPs+and integer SIMD type instructions, or CMOV.++Last, if sound quality is paramount (such as when going from > 16 bits to 16+bits) you probably want to use a higher-order dither function found elsewhere+on this site. +++Code : +// This code will down-convert and dither a 16-bit signed short +// mono signal into an 8-bit unsigned char signal, using a first +// order forward-feeding error term dither. ++#define uchar unsigned char ++void dither_one_channel_16_to_8( short * input, uchar * output, int count, int * memory ) +{ +  int m = *memory; +  while( count-- > 0 ) { +    int i = *input++; +    i += m; +    int j = i + 32768 - 128; +    uchar o; +    if( j < 0 ) { +      o = 0; +    } +    else if( j > 65535 ) { +      o = 255; +    } +    else { +      o = (uchar)((j>>8)&0xff); +    } +    m = ((j-32768+128)-i); +    *output++ = o; +  } +  *memory = m; +} +*/
+ portaudio/src/common/pa_front.c view
@@ -0,0 +1,1770 @@+/*+ * $Id: pa_front.c 1880 2012-12-04 18:39:48Z rbencina $+ * Portable Audio I/O Library Multi-Host API front end+ * Validate function parameters and manage multiple host APIs.+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Implements PortAudio API functions defined in portaudio.h, checks + some errors, delegates platform-specific behavior to host API implementations.+ + Implements the functions defined in the PortAudio API (portaudio.h), + validates some parameters and checks for state inconsistencies before + forwarding API requests to specific Host API implementations (via the + interface declared in pa_hostapi.h), and Streams (via the interface + declared in pa_stream.h).++ This file manages initialization and termination of Host API+ implementations via initializer functions stored in the paHostApiInitializers+ global array (usually defined in an os-specific pa_[os]_hostapis.c file).++ This file maintains a list of all open streams and closes them at Pa_Terminate().++ Some utility functions declared in pa_util.h are implemented in this file.++ All PortAudio API functions can be conditionally compiled with logging code.+ To compile with logging, define the PA_LOG_API_CALLS precompiler symbol.+*/+++#include <stdio.h>+#include <memory.h>+#include <string.h>+#include <assert.h> /* needed by PA_VALIDATE_ENDIANNESS */++#include "portaudio.h"+#include "pa_util.h"+#include "pa_endianness.h"+#include "pa_types.h"+#include "pa_hostapi.h"+#include "pa_stream.h"+#include "pa_trace.h" /* still usefull?*/+#include "pa_debugprint.h"+++#define PA_VERSION_  1899+#define PA_VERSION_TEXT_ "PortAudio V19-devel (built " __DATE__  " " __TIME__ ")"+++++int Pa_GetVersion( void )+{+    return PA_VERSION_;+}+++const char* Pa_GetVersionText( void )+{+    return PA_VERSION_TEXT_;+}++++#define PA_LAST_HOST_ERROR_TEXT_LENGTH_  1024++static char lastHostErrorText_[ PA_LAST_HOST_ERROR_TEXT_LENGTH_ + 1 ] = {0};++static PaHostErrorInfo lastHostErrorInfo_ = { (PaHostApiTypeId)-1, 0, lastHostErrorText_ };+++void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode,+        const char *errorText )+{+    lastHostErrorInfo_.hostApiType = hostApiType;+    lastHostErrorInfo_.errorCode = errorCode;++    strncpy( lastHostErrorText_, errorText, PA_LAST_HOST_ERROR_TEXT_LENGTH_ );+}++++static PaUtilHostApiRepresentation **hostApis_ = 0;+static int hostApisCount_ = 0;+static int defaultHostApiIndex_ = 0;+static int initializationCount_ = 0;+static int deviceCount_ = 0;++PaUtilStreamRepresentation *firstOpenStream_ = NULL;+++#define PA_IS_INITIALISED_ (initializationCount_ != 0)+++static int CountHostApiInitializers( void )+{+    int result = 0;++    while( paHostApiInitializers[ result ] != 0 )+        ++result;+    return result;+}+++static void TerminateHostApis( void )+{+    /* terminate in reverse order from initialization */+    PA_DEBUG(("TerminateHostApis in \n"));++    while( hostApisCount_ > 0 )+    {+        --hostApisCount_;+        hostApis_[hostApisCount_]->Terminate( hostApis_[hostApisCount_] );+    }+    hostApisCount_ = 0;+    defaultHostApiIndex_ = 0;+    deviceCount_ = 0;++    if( hostApis_ != 0 )+        PaUtil_FreeMemory( hostApis_ );+    hostApis_ = 0;++    PA_DEBUG(("TerminateHostApis out\n"));+}+++static PaError InitializeHostApis( void )+{+    PaError result = paNoError;+    int i, initializerCount, baseDeviceIndex;++    initializerCount = CountHostApiInitializers();++    hostApis_ = (PaUtilHostApiRepresentation**)PaUtil_AllocateMemory(+            sizeof(PaUtilHostApiRepresentation*) * initializerCount );+    if( !hostApis_ )+    {+        result = paInsufficientMemory;+        goto error; +    }++    hostApisCount_ = 0;+    defaultHostApiIndex_ = -1; /* indicates that we haven't determined the default host API yet */+    deviceCount_ = 0;+    baseDeviceIndex = 0;++    for( i=0; i< initializerCount; ++i )+    {+        hostApis_[hostApisCount_] = NULL;++        PA_DEBUG(( "before paHostApiInitializers[%d].\n",i));++        result = paHostApiInitializers[i]( &hostApis_[hostApisCount_], hostApisCount_ );+        if( result != paNoError )+            goto error;++        PA_DEBUG(( "after paHostApiInitializers[%d].\n",i));++        if( hostApis_[hostApisCount_] )+        {+            PaUtilHostApiRepresentation* hostApi = hostApis_[hostApisCount_];+            assert( hostApi->info.defaultInputDevice < hostApi->info.deviceCount );+            assert( hostApi->info.defaultOutputDevice < hostApi->info.deviceCount );++            /* the first successfully initialized host API with a default input *or* +               output device is used as the default host API.+            */+            if( (defaultHostApiIndex_ == -1) &&+                    ( hostApi->info.defaultInputDevice != paNoDevice +                        || hostApi->info.defaultOutputDevice != paNoDevice ) )+            {+                defaultHostApiIndex_ = hostApisCount_;+            }++            hostApi->privatePaFrontInfo.baseDeviceIndex = baseDeviceIndex;++            if( hostApi->info.defaultInputDevice != paNoDevice )+                hostApi->info.defaultInputDevice += baseDeviceIndex;++            if( hostApi->info.defaultOutputDevice != paNoDevice )+                hostApi->info.defaultOutputDevice += baseDeviceIndex;++            baseDeviceIndex += hostApi->info.deviceCount;+            deviceCount_ += hostApi->info.deviceCount;++            ++hostApisCount_;+        }+    }++    /* if no host APIs have devices, the default host API is the first initialized host API */+    if( defaultHostApiIndex_ == -1 )+        defaultHostApiIndex_ = 0;++    return result;++error:+    TerminateHostApis();+    return result;+}+++/*+    FindHostApi() finds the index of the host api to which+    <device> belongs and returns it. if <hostSpecificDeviceIndex> is+    non-null, the host specific device index is returned in it.+    returns -1 if <device> is out of range.+ +*/+static int FindHostApi( PaDeviceIndex device, int *hostSpecificDeviceIndex )+{+    int i=0;++    if( !PA_IS_INITIALISED_ )+        return -1;++    if( device < 0 )+        return -1;++    while( i < hostApisCount_+            && device >= hostApis_[i]->info.deviceCount )+    {++        device -= hostApis_[i]->info.deviceCount;+        ++i;+    }++    if( i >= hostApisCount_ )+        return -1;++    if( hostSpecificDeviceIndex )+        *hostSpecificDeviceIndex = device;++    return i;+}+++static void AddOpenStream( PaStream* stream )+{+    ((PaUtilStreamRepresentation*)stream)->nextOpenStream = firstOpenStream_;+    firstOpenStream_ = (PaUtilStreamRepresentation*)stream;+}+++static void RemoveOpenStream( PaStream* stream )+{+    PaUtilStreamRepresentation *previous = NULL;+    PaUtilStreamRepresentation *current = firstOpenStream_;++    while( current != NULL )+    {+        if( ((PaStream*)current) == stream )+        {+            if( previous == NULL )+            {+                firstOpenStream_ = current->nextOpenStream;+            }+            else+            {+                previous->nextOpenStream = current->nextOpenStream;+            }+            return;+        }+        else+        {+            previous = current;+            current = current->nextOpenStream;+        }+    }+}+++static void CloseOpenStreams( void )+{+    /* we call Pa_CloseStream() here to ensure that the same destruction+        logic is used for automatically closed streams */++    while( firstOpenStream_ != NULL )+        Pa_CloseStream( firstOpenStream_ );+}+++PaError Pa_Initialize( void )+{+    PaError result;++    PA_LOGAPI_ENTER( "Pa_Initialize" );++    if( PA_IS_INITIALISED_ )+    {+        ++initializationCount_;+        result = paNoError;+    }+    else+    {+        PA_VALIDATE_TYPE_SIZES;+        PA_VALIDATE_ENDIANNESS;+        +        PaUtil_InitializeClock();+        PaUtil_ResetTraceMessages();++        result = InitializeHostApis();+        if( result == paNoError )+            ++initializationCount_;+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_Initialize", result );++    return result;+}+++PaError Pa_Terminate( void )+{+    PaError result;++    PA_LOGAPI_ENTER( "Pa_Terminate" );++    if( PA_IS_INITIALISED_ )+    {+        if( --initializationCount_ == 0 )+        {+            CloseOpenStreams();++            TerminateHostApis();++            PaUtil_DumpTraceMessages();+        }+        result = paNoError;+    }+    else+    {+        result=  paNotInitialized;+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_Terminate", result );++    return result;+}+++const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void )+{+    return &lastHostErrorInfo_;+}+++const char *Pa_GetErrorText( PaError errorCode )+{+    const char *result;++    switch( errorCode )+    {+    case paNoError:                  result = "Success"; break;+    case paNotInitialized:           result = "PortAudio not initialized"; break;+    /** @todo could catenate the last host error text to result in the case of paUnanticipatedHostError. see: http://www.portaudio.com/trac/ticket/114 */+    case paUnanticipatedHostError:   result = "Unanticipated host error"; break;+    case paInvalidChannelCount:      result = "Invalid number of channels"; break;+    case paInvalidSampleRate:        result = "Invalid sample rate"; break;+    case paInvalidDevice:            result = "Invalid device"; break;+    case paInvalidFlag:              result = "Invalid flag"; break;+    case paSampleFormatNotSupported: result = "Sample format not supported"; break;+    case paBadIODeviceCombination:   result = "Illegal combination of I/O devices"; break;+    case paInsufficientMemory:       result = "Insufficient memory"; break;+    case paBufferTooBig:             result = "Buffer too big"; break;+    case paBufferTooSmall:           result = "Buffer too small"; break;+    case paNullCallback:             result = "No callback routine specified"; break;+    case paBadStreamPtr:             result = "Invalid stream pointer"; break;+    case paTimedOut:                 result = "Wait timed out"; break;+    case paInternalError:            result = "Internal PortAudio error"; break;+    case paDeviceUnavailable:        result = "Device unavailable"; break;+    case paIncompatibleHostApiSpecificStreamInfo:   result = "Incompatible host API specific stream info"; break;+    case paStreamIsStopped:          result = "Stream is stopped"; break;+    case paStreamIsNotStopped:       result = "Stream is not stopped"; break;+    case paInputOverflowed:          result = "Input overflowed"; break;+    case paOutputUnderflowed:        result = "Output underflowed"; break;+    case paHostApiNotFound:          result = "Host API not found"; break;+    case paInvalidHostApi:           result = "Invalid host API"; break;+    case paCanNotReadFromACallbackStream:       result = "Can't read from a callback stream"; break;+    case paCanNotWriteToACallbackStream:        result = "Can't write to a callback stream"; break;+    case paCanNotReadFromAnOutputOnlyStream:    result = "Can't read from an output only stream"; break;+    case paCanNotWriteToAnInputOnlyStream:      result = "Can't write to an input only stream"; break;+    case paIncompatibleStreamHostApi: result = "Incompatible stream host API"; break;+    case paBadBufferPtr:             result = "Bad buffer pointer"; break;+    default:                         +		if( errorCode > 0 )+			result = "Invalid error code (value greater than zero)"; +        else+			result = "Invalid error code"; +        break;+    }+    return result;+}+++PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type )+{+    PaHostApiIndex result;+    int i;+    +    PA_LOGAPI_ENTER_PARAMS( "Pa_HostApiTypeIdToHostApiIndex" );+    PA_LOGAPI(("\tPaHostApiTypeId type: %d\n", type ));++    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;+    }+    else+    {+        result = paHostApiNotFound;+        +        for( i=0; i < hostApisCount_; ++i )+        {+            if( hostApis_[i]->info.type == type )+            {+                result = i;+                break;+            }         +        }+    }++    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_HostApiTypeIdToHostApiIndex", "PaHostApiIndex: %d", result );++    return result;+}+++PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi,+        PaHostApiTypeId type )+{+    PaError result;+    int i;+    +    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;+    }+    else+    {+        result = paHostApiNotFound;+                +        for( i=0; i < hostApisCount_; ++i )+        {+            if( hostApis_[i]->info.type == type )+            {+                *hostApi = hostApis_[i];+                result = paNoError;+                break;+            }+        }+    }++    return result;+}+++PaError PaUtil_DeviceIndexToHostApiDeviceIndex(+        PaDeviceIndex *hostApiDevice, PaDeviceIndex device, struct PaUtilHostApiRepresentation *hostApi )+{+    PaError result;+    PaDeviceIndex x;+    +    x = device - hostApi->privatePaFrontInfo.baseDeviceIndex;++    if( x < 0 || x >= hostApi->info.deviceCount )+    {+        result = paInvalidDevice;+    }+    else+    {+        *hostApiDevice = x;+        result = paNoError;+    }++    return result;+}+++PaHostApiIndex Pa_GetHostApiCount( void )+{+    int result;++    PA_LOGAPI_ENTER( "Pa_GetHostApiCount" );++    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;+    }+    else+    {+        result = hostApisCount_;+    }++    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetHostApiCount", "PaHostApiIndex: %d", result );++    return result;+}+++PaHostApiIndex Pa_GetDefaultHostApi( void )+{+    int result;++    PA_LOGAPI_ENTER( "Pa_GetDefaultHostApi" );++    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;+    }+    else+    {+        result = defaultHostApiIndex_;++        /* internal consistency check: make sure that the default host api+         index is within range */++        if( result < 0 || result >= hostApisCount_ )+        {+            result = paInternalError;+        }+    }++    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetDefaultHostApi", "PaHostApiIndex: %d", result );++    return result;+}+++const PaHostApiInfo* Pa_GetHostApiInfo( PaHostApiIndex hostApi )+{+    PaHostApiInfo *info;++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetHostApiInfo" );+    PA_LOGAPI(("\tPaHostApiIndex hostApi: %d\n", hostApi ));++    if( !PA_IS_INITIALISED_ )+    {+        info = NULL;++        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));+        PA_LOGAPI(("\tPaHostApiInfo*: NULL [ PortAudio not initialized ]\n" ));++    }+    else if( hostApi < 0 || hostApi >= hostApisCount_ )+    {+        info = NULL;+        +        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));+        PA_LOGAPI(("\tPaHostApiInfo*: NULL [ hostApi out of range ]\n" ));++    }+    else+    {+        info = &hostApis_[hostApi]->info;++        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));+        PA_LOGAPI(("\tPaHostApiInfo*: 0x%p\n", info ));+        PA_LOGAPI(("\t{\n" ));+        PA_LOGAPI(("\t\tint structVersion: %d\n", info->structVersion ));+        PA_LOGAPI(("\t\tPaHostApiTypeId type: %d\n", info->type ));+        PA_LOGAPI(("\t\tconst char *name: %s\n", info->name ));+        PA_LOGAPI(("\t}\n" ));++    }++     return info;+}+++PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi, int hostApiDeviceIndex )+{+    PaDeviceIndex result;++    PA_LOGAPI_ENTER_PARAMS( "Pa_HostApiDeviceIndexToPaDeviceIndex" );+    PA_LOGAPI(("\tPaHostApiIndex hostApi: %d\n", hostApi ));+    PA_LOGAPI(("\tint hostApiDeviceIndex: %d\n", hostApiDeviceIndex ));++    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;+    }+    else+    {+        if( hostApi < 0 || hostApi >= hostApisCount_ )+        {+            result = paInvalidHostApi;+        }+        else+        {+            if( hostApiDeviceIndex < 0 ||+                    hostApiDeviceIndex >= hostApis_[hostApi]->info.deviceCount )+            {+                result = paInvalidDevice;+            }+            else+            {+                result = hostApis_[hostApi]->privatePaFrontInfo.baseDeviceIndex + hostApiDeviceIndex;+            }+        }+    }++    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_HostApiDeviceIndexToPaDeviceIndex", "PaDeviceIndex: %d", result );++    return result;+}+++PaDeviceIndex Pa_GetDeviceCount( void )+{+    PaDeviceIndex result;++    PA_LOGAPI_ENTER( "Pa_GetDeviceCount" );++    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;+    }+    else+    {+        result = deviceCount_;+    }++    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetDeviceCount", "PaDeviceIndex: %d", result );++    return result;+}+++PaDeviceIndex Pa_GetDefaultInputDevice( void )+{+    PaHostApiIndex hostApi;+    PaDeviceIndex result;++    PA_LOGAPI_ENTER( "Pa_GetDefaultInputDevice" );++    hostApi = Pa_GetDefaultHostApi();+    if( hostApi < 0 )+    {+        result = paNoDevice;+    }+    else+    {+        result = hostApis_[hostApi]->info.defaultInputDevice;+    }++    PA_LOGAPI_EXIT_T( "Pa_GetDefaultInputDevice", "PaDeviceIndex: %d", result );++    return result;+}+++PaDeviceIndex Pa_GetDefaultOutputDevice( void )+{+    PaHostApiIndex hostApi;+    PaDeviceIndex result;+    +    PA_LOGAPI_ENTER( "Pa_GetDefaultOutputDevice" );++    hostApi = Pa_GetDefaultHostApi();+    if( hostApi < 0 )+    {+        result = paNoDevice;+    }+    else+    {+        result = hostApis_[hostApi]->info.defaultOutputDevice;+    }++    PA_LOGAPI_EXIT_T( "Pa_GetDefaultOutputDevice", "PaDeviceIndex: %d", result );++    return result;+}+++const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device )+{+    int hostSpecificDeviceIndex;+    int hostApiIndex = FindHostApi( device, &hostSpecificDeviceIndex );+    PaDeviceInfo *result;+++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetDeviceInfo" );+    PA_LOGAPI(("\tPaDeviceIndex device: %d\n", device ));++    if( hostApiIndex < 0 )+    {+        result = NULL;++        PA_LOGAPI(("Pa_GetDeviceInfo returned:\n" ));+        PA_LOGAPI(("\tPaDeviceInfo* NULL [ invalid device index ]\n" ));++    }+    else+    {+        result = hostApis_[hostApiIndex]->deviceInfos[ hostSpecificDeviceIndex ];++        PA_LOGAPI(("Pa_GetDeviceInfo returned:\n" ));+        PA_LOGAPI(("\tPaDeviceInfo*: 0x%p:\n", result ));+        PA_LOGAPI(("\t{\n" ));++        PA_LOGAPI(("\t\tint structVersion: %d\n", result->structVersion ));+        PA_LOGAPI(("\t\tconst char *name: %s\n", result->name ));+        PA_LOGAPI(("\t\tPaHostApiIndex hostApi: %d\n", result->hostApi ));+        PA_LOGAPI(("\t\tint maxInputChannels: %d\n", result->maxInputChannels ));+        PA_LOGAPI(("\t\tint maxOutputChannels: %d\n", result->maxOutputChannels ));+        PA_LOGAPI(("\t}\n" ));++    }++    return result;+}+++/*+    SampleFormatIsValid() returns 1 if sampleFormat is a sample format+    defined in portaudio.h, or 0 otherwise.+*/+static int SampleFormatIsValid( PaSampleFormat format )+{+    switch( format & ~paNonInterleaved )+    {+    case paFloat32: return 1;+    case paInt16: return 1;+    case paInt32: return 1;+    case paInt24: return 1;+    case paInt8: return 1;+    case paUInt8: return 1;+    case paCustomFormat: return 1;+    default: return 0;+    }+}++/*+    NOTE: make sure this validation list is kept syncronised with the one in+            pa_hostapi.h++    ValidateOpenStreamParameters() checks that parameters to Pa_OpenStream()+    conform to the expected values as described below. This function is+    also designed to be used with the proposed Pa_IsFormatSupported() function.+    +    There are basically two types of validation that could be performed:+    Generic conformance validation, and device capability mismatch+    validation. This function performs only generic conformance validation.+    Validation that would require knowledge of device capabilities is+    not performed because of potentially complex relationships between+    combinations of parameters - for example, even if the sampleRate+    seems ok, it might not be for a duplex stream - we have no way of+    checking this in an API-neutral way, so we don't try.+ +    On success the function returns PaNoError and fills in hostApi,+    hostApiInputDeviceID, and hostApiOutputDeviceID fields. On failure+    the function returns an error code indicating the first encountered+    parameter error.+ + +    If ValidateOpenStreamParameters() returns paNoError, the following+    assertions are guaranteed to be true.+ +    - at least one of inputParameters & outputParmeters is valid (not NULL)++    - if inputParameters & outputParameters are both valid, that+        inputParameters->device & outputParameters->device  both use the same host api+ +    PaDeviceIndex inputParameters->device+        - is within range (0 to Pa_GetDeviceCount-1) Or:+        - is paUseHostApiSpecificDeviceSpecification and+            inputParameters->hostApiSpecificStreamInfo is non-NULL and refers+            to a valid host api++    int inputParameters->channelCount+        - if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, channelCount is > 0+        - upper bound is NOT validated against device capabilities+ +    PaSampleFormat inputParameters->sampleFormat+        - is one of the sample formats defined in portaudio.h++    void *inputParameters->hostApiSpecificStreamInfo+        - if supplied its hostApi field matches the input device's host Api+ +    PaDeviceIndex outputParmeters->device+        - is within range (0 to Pa_GetDeviceCount-1)+ +    int outputParmeters->channelCount+        - if inputDevice is valid, channelCount is > 0+        - upper bound is NOT validated against device capabilities+ +    PaSampleFormat outputParmeters->sampleFormat+        - is one of the sample formats defined in portaudio.h+        +    void *outputParmeters->hostApiSpecificStreamInfo+        - if supplied its hostApi field matches the output device's host Api+ +    double sampleRate+        - is not an 'absurd' rate (less than 1000. or greater than 384000.)+        - sampleRate is NOT validated against device capabilities+ +    PaStreamFlags streamFlags+        - unused platform neutral flags are zero+        - paNeverDropInput is only used for full-duplex callback streams with+            variable buffer size (paFramesPerBufferUnspecified)+*/+static PaError ValidateOpenStreamParameters(+    const PaStreamParameters *inputParameters,+    const PaStreamParameters *outputParameters,+    double sampleRate,+    unsigned long framesPerBuffer,+    PaStreamFlags streamFlags,+    PaStreamCallback *streamCallback,+    PaUtilHostApiRepresentation **hostApi,+    PaDeviceIndex *hostApiInputDevice,+    PaDeviceIndex *hostApiOutputDevice )+{+    int inputHostApiIndex  = -1, /* Surpress uninitialised var warnings: compiler does */+        outputHostApiIndex = -1; /* not see that if inputParameters and outputParame-  */+                                 /* ters are both nonzero, these indices are set.      */++    if( (inputParameters == NULL) && (outputParameters == NULL) )+    {+        return paInvalidDevice; /** @todo should be a new error code "invalid device parameters" or something */+    }+    else+    {+        if( inputParameters == NULL )+        {+            *hostApiInputDevice = paNoDevice;+        }+        else if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )+        {+            if( inputParameters->hostApiSpecificStreamInfo )+            {+                inputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex(+                        ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType );++                if( inputHostApiIndex != -1 )+                {+                    *hostApiInputDevice = paUseHostApiSpecificDeviceSpecification;+                    *hostApi = hostApis_[inputHostApiIndex];+                }+                else+                {+                    return paInvalidDevice;+                }+            }+            else+            {+                return paInvalidDevice;+            }+        }+        else+        {+            if( inputParameters->device < 0 || inputParameters->device >= deviceCount_ )+                return paInvalidDevice;++            inputHostApiIndex = FindHostApi( inputParameters->device, hostApiInputDevice );+            if( inputHostApiIndex < 0 )+                return paInternalError;++            *hostApi = hostApis_[inputHostApiIndex];++            if( inputParameters->channelCount <= 0 )+                return paInvalidChannelCount;++            if( !SampleFormatIsValid( inputParameters->sampleFormat ) )+                return paSampleFormatNotSupported;++            if( inputParameters->hostApiSpecificStreamInfo != NULL )+            {+                if( ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType+                        != (*hostApi)->info.type )+                    return paIncompatibleHostApiSpecificStreamInfo;+            }+        }++        if( outputParameters == NULL )+        {+            *hostApiOutputDevice = paNoDevice;+        }+        else if( outputParameters->device == paUseHostApiSpecificDeviceSpecification  )+        {+            if( outputParameters->hostApiSpecificStreamInfo )+            {+                outputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex(+                        ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType );++                if( outputHostApiIndex != -1 )+                {+                    *hostApiOutputDevice = paUseHostApiSpecificDeviceSpecification;+                    *hostApi = hostApis_[outputHostApiIndex];+                }+                else+                {+                    return paInvalidDevice;+                }+            }+            else+            {+                return paInvalidDevice;+            }+        }+        else+        {+            if( outputParameters->device < 0 || outputParameters->device >= deviceCount_ )+                return paInvalidDevice;++            outputHostApiIndex = FindHostApi( outputParameters->device, hostApiOutputDevice );+            if( outputHostApiIndex < 0 )+                return paInternalError;++            *hostApi = hostApis_[outputHostApiIndex];++            if( outputParameters->channelCount <= 0 )+                return paInvalidChannelCount;++            if( !SampleFormatIsValid( outputParameters->sampleFormat ) )+                return paSampleFormatNotSupported;++            if( outputParameters->hostApiSpecificStreamInfo != NULL )+            {+                if( ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType+                        != (*hostApi)->info.type )+                    return paIncompatibleHostApiSpecificStreamInfo;+            }+        }   ++        if( (inputParameters != NULL) && (outputParameters != NULL) )+        {+            /* ensure that both devices use the same API */+            if( inputHostApiIndex != outputHostApiIndex )+                return paBadIODeviceCombination;+        }+    }+    +    +    /* Check for absurd sample rates. */+    if( (sampleRate < 1000.0) || (sampleRate > 384000.0) )+        return paInvalidSampleRate;++    if( ((streamFlags & ~paPlatformSpecificFlags) & ~(paClipOff | paDitherOff | paNeverDropInput | paPrimeOutputBuffersUsingStreamCallback ) ) != 0 )+        return paInvalidFlag;++    if( streamFlags & paNeverDropInput )+    {+        /* must be a callback stream */+        if( !streamCallback )+             return paInvalidFlag;++        /* must be a full duplex stream */+        if( (inputParameters == NULL) || (outputParameters == NULL) )+            return paInvalidFlag;++        /* must use paFramesPerBufferUnspecified */+        if( framesPerBuffer != paFramesPerBufferUnspecified )+            return paInvalidFlag;+    }+    +    return paNoError;+}+++PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters,+                              const PaStreamParameters *outputParameters,+                              double sampleRate )+{+    PaError result;+    PaUtilHostApiRepresentation *hostApi = 0;+    PaDeviceIndex hostApiInputDevice = paNoDevice, hostApiOutputDevice = paNoDevice;+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;+++#ifdef PA_LOG_API_CALLS+    PA_LOGAPI_ENTER_PARAMS( "Pa_IsFormatSupported" );++    if( inputParameters == NULL ){+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: NULL\n" ));+    }else{+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ));+        PA_LOGAPI(("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ));+        PA_LOGAPI(("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ));+        PA_LOGAPI(("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ));+        PA_LOGAPI(("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ));+        PA_LOGAPI(("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ));+    }++    if( outputParameters == NULL ){+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: NULL\n" ));+    }else{+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ));+        PA_LOGAPI(("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ));+        PA_LOGAPI(("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ));+        PA_LOGAPI(("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ));+        PA_LOGAPI(("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ));+        PA_LOGAPI(("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ));+    }+    +    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));+#endif++    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;++        PA_LOGAPI_EXIT_PAERROR( "Pa_IsFormatSupported", result );+        return result;+    }++    result = ValidateOpenStreamParameters( inputParameters,+                                           outputParameters,+                                           sampleRate, 0, paNoFlag, 0,+                                           &hostApi,+                                           &hostApiInputDevice,+                                           &hostApiOutputDevice );+    if( result != paNoError )+    {+        PA_LOGAPI_EXIT_PAERROR( "Pa_IsFormatSupported", result );+        return result;+    }+    ++    if( inputParameters )+    {+        hostApiInputParameters.device = hostApiInputDevice;+        hostApiInputParameters.channelCount = inputParameters->channelCount;+        hostApiInputParameters.sampleFormat = inputParameters->sampleFormat;+        hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency;+        hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo;+        hostApiInputParametersPtr = &hostApiInputParameters;+    }+    else+    {+        hostApiInputParametersPtr = NULL;+    }++    if( outputParameters )+    {+        hostApiOutputParameters.device = hostApiOutputDevice;+        hostApiOutputParameters.channelCount = outputParameters->channelCount;+        hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat;+        hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency;+        hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo;+        hostApiOutputParametersPtr = &hostApiOutputParameters;+    }+    else+    {+        hostApiOutputParametersPtr = NULL;+    }++    result = hostApi->IsFormatSupported( hostApi,+                                  hostApiInputParametersPtr, hostApiOutputParametersPtr,+                                  sampleRate );++#ifdef PA_LOG_API_CALLS+    PA_LOGAPI(("Pa_OpenStream returned:\n" ));+    if( result == paFormatIsSupported )+        PA_LOGAPI(("\tPaError: 0 [ paFormatIsSupported ]\n" ));+    else+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));+#endif++    return result;+}+++PaError Pa_OpenStream( PaStream** stream,+                       const PaStreamParameters *inputParameters,+                       const PaStreamParameters *outputParameters,+                       double sampleRate,+                       unsigned long framesPerBuffer,+                       PaStreamFlags streamFlags,+                       PaStreamCallback *streamCallback,+                       void *userData )+{+    PaError result;+    PaUtilHostApiRepresentation *hostApi = 0;+    PaDeviceIndex hostApiInputDevice = paNoDevice, hostApiOutputDevice = paNoDevice;+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;+++#ifdef PA_LOG_API_CALLS+    PA_LOGAPI_ENTER_PARAMS( "Pa_OpenStream" );+    PA_LOGAPI(("\tPaStream** stream: 0x%p\n", stream ));++    if( inputParameters == NULL ){+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: NULL\n" ));+    }else{+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ));+        PA_LOGAPI(("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ));+        PA_LOGAPI(("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ));+        PA_LOGAPI(("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ));+        PA_LOGAPI(("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ));+        PA_LOGAPI(("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ));+    }++    if( outputParameters == NULL ){+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: NULL\n" ));+    }else{+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ));+        PA_LOGAPI(("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ));+        PA_LOGAPI(("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ));+        PA_LOGAPI(("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ));+        PA_LOGAPI(("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ));+        PA_LOGAPI(("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ));+    }+    +    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));+    PA_LOGAPI(("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ));+    PA_LOGAPI(("\tPaStreamFlags streamFlags: 0x%x\n", streamFlags ));+    PA_LOGAPI(("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ));+    PA_LOGAPI(("\tvoid *userData: 0x%p\n", userData ));+#endif++    if( !PA_IS_INITIALISED_ )+    {+        result = paNotInitialized;++        PA_LOGAPI(("Pa_OpenStream returned:\n" ));+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));+        return result;+    }++    /* Check for parameter errors.+        NOTE: make sure this validation list is kept syncronised with the one+        in pa_hostapi.h+    */++    if( stream == NULL )+    {+        result = paBadStreamPtr;++        PA_LOGAPI(("Pa_OpenStream returned:\n" ));+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));+        return result;+    }++    result = ValidateOpenStreamParameters( inputParameters,+                                           outputParameters,+                                           sampleRate, framesPerBuffer,+                                           streamFlags, streamCallback,+                                           &hostApi,+                                           &hostApiInputDevice,+                                           &hostApiOutputDevice );+    if( result != paNoError )+    {+        PA_LOGAPI(("Pa_OpenStream returned:\n" ));+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));+        return result;+    }+    ++    if( inputParameters )+    {+        hostApiInputParameters.device = hostApiInputDevice;+        hostApiInputParameters.channelCount = inputParameters->channelCount;+        hostApiInputParameters.sampleFormat = inputParameters->sampleFormat;+        hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency;+        hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo;+        hostApiInputParametersPtr = &hostApiInputParameters;+    }+    else+    {+        hostApiInputParametersPtr = NULL;+    }++    if( outputParameters )+    {+        hostApiOutputParameters.device = hostApiOutputDevice;+        hostApiOutputParameters.channelCount = outputParameters->channelCount;+        hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat;+        hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency;+        hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo;+        hostApiOutputParametersPtr = &hostApiOutputParameters;+    }+    else+    {+        hostApiOutputParametersPtr = NULL;+    }++    result = hostApi->OpenStream( hostApi, stream,+                                  hostApiInputParametersPtr, hostApiOutputParametersPtr,+                                  sampleRate, framesPerBuffer, streamFlags, streamCallback, userData );++    if( result == paNoError )+        AddOpenStream( *stream );+++    PA_LOGAPI(("Pa_OpenStream returned:\n" ));+    PA_LOGAPI(("\t*(PaStream** stream): 0x%p\n", *stream ));+    PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));++    return result;+}+++PaError Pa_OpenDefaultStream( PaStream** stream,+                              int inputChannelCount,+                              int outputChannelCount,+                              PaSampleFormat sampleFormat,+                              double sampleRate,+                              unsigned long framesPerBuffer,+                              PaStreamCallback *streamCallback,+                              void *userData )+{+    PaError result;+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;++    PA_LOGAPI_ENTER_PARAMS( "Pa_OpenDefaultStream" );+    PA_LOGAPI(("\tPaStream** stream: 0x%p\n", stream ));+    PA_LOGAPI(("\tint inputChannelCount: %d\n", inputChannelCount ));+    PA_LOGAPI(("\tint outputChannelCount: %d\n", outputChannelCount ));+    PA_LOGAPI(("\tPaSampleFormat sampleFormat: %d\n", sampleFormat ));+    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));+    PA_LOGAPI(("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ));+    PA_LOGAPI(("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ));+    PA_LOGAPI(("\tvoid *userData: 0x%p\n", userData ));+++    if( inputChannelCount > 0 )+    {+        hostApiInputParameters.device = Pa_GetDefaultInputDevice();+		if( hostApiInputParameters.device == paNoDevice )+			return paDeviceUnavailable; +	+        hostApiInputParameters.channelCount = inputChannelCount;+        hostApiInputParameters.sampleFormat = sampleFormat;+        /* defaultHighInputLatency is used below instead of+           defaultLowInputLatency because it is more important for the default+           stream to work reliably than it is for it to work with the lowest+           latency.+         */+        hostApiInputParameters.suggestedLatency = +             Pa_GetDeviceInfo( hostApiInputParameters.device )->defaultHighInputLatency;+        hostApiInputParameters.hostApiSpecificStreamInfo = NULL;+        hostApiInputParametersPtr = &hostApiInputParameters;+    }+    else+    {+        hostApiInputParametersPtr = NULL;+    }++    if( outputChannelCount > 0 )+    {+        hostApiOutputParameters.device = Pa_GetDefaultOutputDevice();+		if( hostApiOutputParameters.device == paNoDevice )+			return paDeviceUnavailable; ++        hostApiOutputParameters.channelCount = outputChannelCount;+        hostApiOutputParameters.sampleFormat = sampleFormat;+        /* defaultHighOutputLatency is used below instead of+           defaultLowOutputLatency because it is more important for the default+           stream to work reliably than it is for it to work with the lowest+           latency.+         */+        hostApiOutputParameters.suggestedLatency =+             Pa_GetDeviceInfo( hostApiOutputParameters.device )->defaultHighOutputLatency;+        hostApiOutputParameters.hostApiSpecificStreamInfo = NULL;+        hostApiOutputParametersPtr = &hostApiOutputParameters;+    }+    else+    {+        hostApiOutputParametersPtr = NULL;+    }+++    result = Pa_OpenStream(+                 stream, hostApiInputParametersPtr, hostApiOutputParametersPtr,+                 sampleRate, framesPerBuffer, paNoFlag, streamCallback, userData );++    PA_LOGAPI(("Pa_OpenDefaultStream returned:\n" ));+    PA_LOGAPI(("\t*(PaStream** stream): 0x%p", *stream ));+    PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));++    return result;+}+++PaError PaUtil_ValidateStreamPointer( PaStream* stream )+{+    if( !PA_IS_INITIALISED_ ) return paNotInitialized;++    if( stream == NULL ) return paBadStreamPtr;++    if( ((PaUtilStreamRepresentation*)stream)->magic != PA_STREAM_MAGIC )+        return paBadStreamPtr;++    return paNoError;+}+++PaError Pa_CloseStream( PaStream* stream )+{+    PaUtilStreamInterface *interface;+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_CloseStream" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    /* always remove the open stream from our list, even if this function+        eventually returns an error. Otherwise CloseOpenStreams() will+        get stuck in an infinite loop */+    RemoveOpenStream( stream ); /* be sure to call this _before_ closing the stream */++    if( result == paNoError )+    {+        interface = PA_STREAM_INTERFACE(stream);++        /* abort the stream if it isn't stopped */+        result = interface->IsStopped( stream );+        if( result == 1 )+            result = paNoError;+        else if( result == 0 )+            result = interface->Abort( stream );++        if( result == paNoError )                 /** @todo REVIEW: shouldn't we close anyway? see: http://www.portaudio.com/trac/ticket/115 */+            result = interface->Close( stream );+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_CloseStream", result );++    return result;+}+++PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_SetStreamFinishedCallback" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));+    PA_LOGAPI(("\tPaStreamFinishedCallback* streamFinishedCallback: 0x%p\n", streamFinishedCallback ));++    if( result == paNoError )+    {+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );+        if( result == 0 )+        {+            result = paStreamIsNotStopped ;+        }+        if( result == 1 )+        {+            PA_STREAM_REP( stream )->streamFinishedCallback = streamFinishedCallback;+            result = paNoError;+        }+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_SetStreamFinishedCallback", result );++    return result;++}+++PaError Pa_StartStream( PaStream *stream )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_StartStream" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( result == paNoError )+    {+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );+        if( result == 0 )+        {+            result = paStreamIsNotStopped ;+        }+        else if( result == 1 )+        {+            result = PA_STREAM_INTERFACE(stream)->Start( stream );+        }+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_StartStream", result );++    return result;+}+++PaError Pa_StopStream( PaStream *stream )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_StopStream" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( result == paNoError )+    {+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );+        if( result == 0 )+        {+            result = PA_STREAM_INTERFACE(stream)->Stop( stream );+        }+        else if( result == 1 )+        {+            result = paStreamIsStopped;+        }+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_StopStream", result );++    return result;+}+++PaError Pa_AbortStream( PaStream *stream )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_AbortStream" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( result == paNoError )+    {+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );+        if( result == 0 )+        {+            result = PA_STREAM_INTERFACE(stream)->Abort( stream );+        }+        else if( result == 1 )+        {+            result = paStreamIsStopped;+        }+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_AbortStream", result );++    return result;+}+++PaError Pa_IsStreamStopped( PaStream *stream )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_IsStreamStopped" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( result == paNoError )+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );++    PA_LOGAPI_EXIT_PAERROR( "Pa_IsStreamStopped", result );++    return result;+}+++PaError Pa_IsStreamActive( PaStream *stream )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_IsStreamActive" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( result == paNoError )+        result = PA_STREAM_INTERFACE(stream)->IsActive( stream );+++    PA_LOGAPI_EXIT_PAERROR( "Pa_IsStreamActive", result );++    return result;+}+++const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream )+{+    PaError error = PaUtil_ValidateStreamPointer( stream );+    const PaStreamInfo *result;++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamInfo" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( error != paNoError )+    {+        result = 0;++        PA_LOGAPI(("Pa_GetStreamInfo returned:\n" ));+        PA_LOGAPI(("\tconst PaStreamInfo*: 0 [PaError error:%d ( %s )]\n", error, Pa_GetErrorText( error ) ));++    }+    else+    {+        result = &PA_STREAM_REP( stream )->streamInfo;++        PA_LOGAPI(("Pa_GetStreamInfo returned:\n" ));+        PA_LOGAPI(("\tconst PaStreamInfo*: 0x%p:\n", result ));+        PA_LOGAPI(("\t{" ));++        PA_LOGAPI(("\t\tint structVersion: %d\n", result->structVersion ));+        PA_LOGAPI(("\t\tPaTime inputLatency: %f\n", result->inputLatency ));+        PA_LOGAPI(("\t\tPaTime outputLatency: %f\n", result->outputLatency ));+        PA_LOGAPI(("\t\tdouble sampleRate: %f\n", result->sampleRate ));+        PA_LOGAPI(("\t}\n" ));++    }++    return result;+}+++PaTime Pa_GetStreamTime( PaStream *stream )+{+    PaError error = PaUtil_ValidateStreamPointer( stream );+    PaTime result;++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamTime" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( error != paNoError )+    {+        result = 0;++        PA_LOGAPI(("Pa_GetStreamTime returned:\n" ));+        PA_LOGAPI(("\tPaTime: 0 [PaError error:%d ( %s )]\n", result, error, Pa_GetErrorText( error ) ));++    }+    else+    {+        result = PA_STREAM_INTERFACE(stream)->GetTime( stream );++        PA_LOGAPI(("Pa_GetStreamTime returned:\n" ));+        PA_LOGAPI(("\tPaTime: %g\n", result ));++    }++    return result;+}+++double Pa_GetStreamCpuLoad( PaStream* stream )+{+    PaError error = PaUtil_ValidateStreamPointer( stream );+    double result;++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamCpuLoad" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( error != paNoError )+    {++        result = 0.0;++        PA_LOGAPI(("Pa_GetStreamCpuLoad returned:\n" ));+        PA_LOGAPI(("\tdouble: 0.0 [PaError error: %d ( %s )]\n", error, Pa_GetErrorText( error ) ));++    }+    else+    {+        result = PA_STREAM_INTERFACE(stream)->GetCpuLoad( stream );++        PA_LOGAPI(("Pa_GetStreamCpuLoad returned:\n" ));+        PA_LOGAPI(("\tdouble: %g\n", result ));++    }++    return result;+}+++PaError Pa_ReadStream( PaStream* stream,+                       void *buffer,+                       unsigned long frames )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_ReadStream" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( result == paNoError )+    {+        if( frames == 0 )+        {+            /* @todo Should we not allow the implementation to signal any overflow condition? see: http://www.portaudio.com/trac/ticket/116*/+            result = paNoError;+        }+        else if( buffer == 0 )+        {+            result = paBadBufferPtr;+        }+        else+        {+            result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );+            if( result == 0 )+            {+                result = PA_STREAM_INTERFACE(stream)->Read( stream, buffer, frames );+            }+            else if( result == 1 )+            {+                result = paStreamIsStopped;+            }+        }+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_ReadStream", result );++    return result;+}+++PaError Pa_WriteStream( PaStream* stream,+                        const void *buffer,+                        unsigned long frames )+{+    PaError result = PaUtil_ValidateStreamPointer( stream );++    PA_LOGAPI_ENTER_PARAMS( "Pa_WriteStream" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( result == paNoError )+    {+        if( frames == 0 )+        {+            /* @todo Should we not allow the implementation to signal any underflow condition? see: http://www.portaudio.com/trac/ticket/116*/+            result = paNoError;+        }+        else if( buffer == 0 )+        {+            result = paBadBufferPtr;+        }+        else+        {+            result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );+            if( result == 0 )+            {+                result = PA_STREAM_INTERFACE(stream)->Write( stream, buffer, frames );+            }+            else if( result == 1 )+            {+                result = paStreamIsStopped;+            }  +        }+    }++    PA_LOGAPI_EXIT_PAERROR( "Pa_WriteStream", result );++    return result;+}++signed long Pa_GetStreamReadAvailable( PaStream* stream )+{+    PaError error = PaUtil_ValidateStreamPointer( stream );+    signed long result;++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamReadAvailable" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( error != paNoError )+    {+        result = 0;++        PA_LOGAPI(("Pa_GetStreamReadAvailable returned:\n" ));+        PA_LOGAPI(("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n", error, Pa_GetErrorText( error ) ));++    }+    else+    {+        result = PA_STREAM_INTERFACE(stream)->GetReadAvailable( stream );++        PA_LOGAPI(("Pa_GetStreamReadAvailable returned:\n" ));+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));++    }++    return result;+}+++signed long Pa_GetStreamWriteAvailable( PaStream* stream )+{+    PaError error = PaUtil_ValidateStreamPointer( stream );+    signed long result;++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamWriteAvailable" );+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));++    if( error != paNoError )+    {+        result = 0;++        PA_LOGAPI(("Pa_GetStreamWriteAvailable returned:\n" ));+        PA_LOGAPI(("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n", error, Pa_GetErrorText( error ) ));++    }+    else+    {+        result = PA_STREAM_INTERFACE(stream)->GetWriteAvailable( stream );++        PA_LOGAPI(("Pa_GetStreamWriteAvailable returned:\n" ));+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));++    }++    return result;+}+++PaError Pa_GetSampleSize( PaSampleFormat format )+{+    int result;++    PA_LOGAPI_ENTER_PARAMS( "Pa_GetSampleSize" );+    PA_LOGAPI(("\tPaSampleFormat format: %d\n", format ));++    switch( format & ~paNonInterleaved )+    {++    case paUInt8:+    case paInt8:+        result = 1;+        break;++    case paInt16:+        result = 2;+        break;++    case paInt24:+        result = 3;+        break;++    case paFloat32:+    case paInt32:+        result = 4;+        break;++    default:+        result = paSampleFormatNotSupported;+        break;+    }++    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetSampleSize", "int: %d", result );++    return (PaError) result;+}+
+ portaudio/src/common/pa_process.c view
@@ -0,0 +1,1829 @@+/*+ * $Id: pa_process.c 1913 2013-11-18 11:42:27Z gineera $+ * Portable Audio I/O Library+ * streamCallback <-> host buffer processing adapter+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Buffer Processor implementation.+*/+++#include <assert.h>+#include <string.h> /* memset() */++#include "pa_process.h"+#include "pa_util.h"+++#define PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_    1024++#define PA_MIN_( a, b ) ( ((a)<(b)) ? (a) : (b) )+++/* greatest common divisor - PGCD in French */+static unsigned long GCD( unsigned long a, unsigned long b )+{+    return (b==0) ? a : GCD( b, a%b);+}++/* least common multiple - PPCM in French */+static unsigned long LCM( unsigned long a, unsigned long b )+{+    return (a*b) / GCD(a,b);+}++#define PA_MAX_( a, b ) (((a) > (b)) ? (a) : (b))++static unsigned long CalculateFrameShift( unsigned long M, unsigned long N )+{+    unsigned long result = 0;+    unsigned long i;+    unsigned long lcm;++    assert( M > 0 );+    assert( N > 0 );++    lcm = LCM( M, N );+    for( i = M; i < lcm; i += M )+        result = PA_MAX_( result, i % N );++    return result;+}+++PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bp,+        int inputChannelCount, PaSampleFormat userInputSampleFormat,+        PaSampleFormat hostInputSampleFormat,+        int outputChannelCount, PaSampleFormat userOutputSampleFormat,+        PaSampleFormat hostOutputSampleFormat,+        double sampleRate,+        PaStreamFlags streamFlags,+        unsigned long framesPerUserBuffer,+        unsigned long framesPerHostBuffer,+        PaUtilHostBufferSizeMode hostBufferSizeMode,+        PaStreamCallback *streamCallback, void *userData )+{+    PaError result = paNoError;+    PaError bytesPerSample;+    unsigned long tempInputBufferSize, tempOutputBufferSize;+    PaStreamFlags tempInputStreamFlags;++    if( streamFlags & paNeverDropInput )+    {+        /* paNeverDropInput is only valid for full-duplex callback streams, with an unspecified number of frames per buffer. */+        if( !streamCallback || !(inputChannelCount > 0 && outputChannelCount > 0) ||+                framesPerUserBuffer != paFramesPerBufferUnspecified )+            return paInvalidFlag;+    }++    /* initialize buffer ptrs to zero so they can be freed if necessary in error */+    bp->tempInputBuffer = 0;+    bp->tempInputBufferPtrs = 0;+    bp->tempOutputBuffer = 0;+    bp->tempOutputBufferPtrs = 0;++    bp->framesPerUserBuffer = framesPerUserBuffer;+    bp->framesPerHostBuffer = framesPerHostBuffer;++    bp->inputChannelCount = inputChannelCount;+    bp->outputChannelCount = outputChannelCount;++    bp->hostBufferSizeMode = hostBufferSizeMode;++    bp->hostInputChannels[0] = bp->hostInputChannels[1] = 0;+    bp->hostOutputChannels[0] = bp->hostOutputChannels[1] = 0;++    if( framesPerUserBuffer == 0 ) /* streamCallback will accept any buffer size */+    {+        bp->useNonAdaptingProcess = 1;+        bp->initialFramesInTempInputBuffer = 0;+        bp->initialFramesInTempOutputBuffer = 0;++        if( hostBufferSizeMode == paUtilFixedHostBufferSize+                || hostBufferSizeMode == paUtilBoundedHostBufferSize )+        {+            bp->framesPerTempBuffer = framesPerHostBuffer;+        }+        else /* unknown host buffer size */+        {+             bp->framesPerTempBuffer = PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_;+        }+    }+    else+    {+        bp->framesPerTempBuffer = framesPerUserBuffer;++        if( hostBufferSizeMode == paUtilFixedHostBufferSize+                && framesPerHostBuffer % framesPerUserBuffer == 0 )+        {+            bp->useNonAdaptingProcess = 1;+            bp->initialFramesInTempInputBuffer = 0;+            bp->initialFramesInTempOutputBuffer = 0;+        }+        else+        {+            bp->useNonAdaptingProcess = 0;++            if( inputChannelCount > 0 && outputChannelCount > 0 )+            {+                /* full duplex */+                if( hostBufferSizeMode == paUtilFixedHostBufferSize )+                {+                    unsigned long frameShift =+                        CalculateFrameShift( framesPerHostBuffer, framesPerUserBuffer );++                    if( framesPerUserBuffer > framesPerHostBuffer )+                    {+                        bp->initialFramesInTempInputBuffer = frameShift;+                        bp->initialFramesInTempOutputBuffer = 0;+                    }+                    else+                    {+                        bp->initialFramesInTempInputBuffer = 0;+                        bp->initialFramesInTempOutputBuffer = frameShift;+                    }+                }+                else /* variable host buffer size, add framesPerUserBuffer latency */+                {+                    bp->initialFramesInTempInputBuffer = 0;+                    bp->initialFramesInTempOutputBuffer = framesPerUserBuffer;+                }+            }+            else+            {+                /* half duplex */+                bp->initialFramesInTempInputBuffer = 0;+                bp->initialFramesInTempOutputBuffer = 0;+            }+        }+    }+++    bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer;+    bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer;++    +    if( inputChannelCount > 0 )+    {+        bytesPerSample = Pa_GetSampleSize( hostInputSampleFormat );+        if( bytesPerSample > 0 )+        {+            bp->bytesPerHostInputSample = bytesPerSample;+        }+        else+        {+            result = bytesPerSample;+            goto error;+        }++        bytesPerSample = Pa_GetSampleSize( userInputSampleFormat );+        if( bytesPerSample > 0 )+        {+            bp->bytesPerUserInputSample = bytesPerSample;+        }+        else+        {+            result = bytesPerSample;+            goto error;+        }++        /* Under the assumption that no ADC in existence delivers better than 24bits resolution,+            we disable dithering when host input format is paInt32 and user format is paInt24, +            since the host samples will just be padded with zeros anyway. */++        tempInputStreamFlags = streamFlags;+        if( !(tempInputStreamFlags & paDitherOff) /* dither is on */+                && (hostInputSampleFormat & paInt32) /* host input format is int32 */+                && (userInputSampleFormat & paInt24) /* user requested format is int24 */ ){++            tempInputStreamFlags = tempInputStreamFlags | paDitherOff;+        }++        bp->inputConverter =+            PaUtil_SelectConverter( hostInputSampleFormat, userInputSampleFormat, tempInputStreamFlags );++        bp->inputZeroer = PaUtil_SelectZeroer( userInputSampleFormat );+            +        bp->userInputIsInterleaved = (userInputSampleFormat & paNonInterleaved)?0:1;+		+        bp->hostInputIsInterleaved = (hostInputSampleFormat & paNonInterleaved)?0:1;++        bp->userInputSampleFormatIsEqualToHost = ((userInputSampleFormat & ~paNonInterleaved) == (hostInputSampleFormat & ~paNonInterleaved));++        tempInputBufferSize =+            bp->framesPerTempBuffer * bp->bytesPerUserInputSample * inputChannelCount;+         +        bp->tempInputBuffer = PaUtil_AllocateMemory( tempInputBufferSize );+        if( bp->tempInputBuffer == 0 )+        {+            result = paInsufficientMemory;+            goto error;+        }+        +        if( bp->framesInTempInputBuffer > 0 )+            memset( bp->tempInputBuffer, 0, tempInputBufferSize );++        if( userInputSampleFormat & paNonInterleaved )+        {+            bp->tempInputBufferPtrs =+                (void **)PaUtil_AllocateMemory( sizeof(void*)*inputChannelCount );+            if( bp->tempInputBufferPtrs == 0 )+            {+                result = paInsufficientMemory;+                goto error;+            }+        }++        bp->hostInputChannels[0] = (PaUtilChannelDescriptor*)+                PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor) * inputChannelCount * 2);+        if( bp->hostInputChannels[0] == 0 )+        {+            result = paInsufficientMemory;+            goto error;+        }++        bp->hostInputChannels[1] = &bp->hostInputChannels[0][inputChannelCount];+    }++    if( outputChannelCount > 0 )+    {+        bytesPerSample = Pa_GetSampleSize( hostOutputSampleFormat );+        if( bytesPerSample > 0 )+        {+            bp->bytesPerHostOutputSample = bytesPerSample;+        }+        else+        {+            result = bytesPerSample;+            goto error;+        }++        bytesPerSample = Pa_GetSampleSize( userOutputSampleFormat );+        if( bytesPerSample > 0 )+        {+            bp->bytesPerUserOutputSample = bytesPerSample;+        }+        else+        {+            result = bytesPerSample;+            goto error;+        }++        bp->outputConverter =+            PaUtil_SelectConverter( userOutputSampleFormat, hostOutputSampleFormat, streamFlags );++        bp->outputZeroer = PaUtil_SelectZeroer( hostOutputSampleFormat );++        bp->userOutputIsInterleaved = (userOutputSampleFormat & paNonInterleaved)?0:1;++        bp->hostOutputIsInterleaved = (hostOutputSampleFormat & paNonInterleaved)?0:1;++        bp->userOutputSampleFormatIsEqualToHost = ((userOutputSampleFormat & ~paNonInterleaved) == (hostOutputSampleFormat & ~paNonInterleaved));++        tempOutputBufferSize =+                bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * outputChannelCount;++        bp->tempOutputBuffer = PaUtil_AllocateMemory( tempOutputBufferSize );+        if( bp->tempOutputBuffer == 0 )+        {+            result = paInsufficientMemory;+            goto error;+        }++        if( bp->framesInTempOutputBuffer > 0 )+            memset( bp->tempOutputBuffer, 0, tempOutputBufferSize );+        +        if( userOutputSampleFormat & paNonInterleaved )+        {+            bp->tempOutputBufferPtrs =+                (void **)PaUtil_AllocateMemory( sizeof(void*)*outputChannelCount );+            if( bp->tempOutputBufferPtrs == 0 )+            {+                result = paInsufficientMemory;+                goto error;+            }+        }++        bp->hostOutputChannels[0] = (PaUtilChannelDescriptor*)+                PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor)*outputChannelCount * 2 );+        if( bp->hostOutputChannels[0] == 0 )+        {                                                                     +            result = paInsufficientMemory;+            goto error;+        }++        bp->hostOutputChannels[1] = &bp->hostOutputChannels[0][outputChannelCount];+    }++    PaUtil_InitializeTriangularDitherState( &bp->ditherGenerator );++    bp->samplePeriod = 1. / sampleRate;++    bp->streamCallback = streamCallback;+    bp->userData = userData;++    return result;++error:+    if( bp->tempInputBuffer )+        PaUtil_FreeMemory( bp->tempInputBuffer );++    if( bp->tempInputBufferPtrs )+        PaUtil_FreeMemory( bp->tempInputBufferPtrs );++    if( bp->hostInputChannels[0] )+        PaUtil_FreeMemory( bp->hostInputChannels[0] );++    if( bp->tempOutputBuffer )+        PaUtil_FreeMemory( bp->tempOutputBuffer );++    if( bp->tempOutputBufferPtrs )+        PaUtil_FreeMemory( bp->tempOutputBufferPtrs );++    if( bp->hostOutputChannels[0] )+        PaUtil_FreeMemory( bp->hostOutputChannels[0] );++    return result;+}+++void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bp )+{+    if( bp->tempInputBuffer )+        PaUtil_FreeMemory( bp->tempInputBuffer );++    if( bp->tempInputBufferPtrs )+        PaUtil_FreeMemory( bp->tempInputBufferPtrs );++    if( bp->hostInputChannels[0] )+        PaUtil_FreeMemory( bp->hostInputChannels[0] );+        +    if( bp->tempOutputBuffer )+        PaUtil_FreeMemory( bp->tempOutputBuffer );++    if( bp->tempOutputBufferPtrs )+        PaUtil_FreeMemory( bp->tempOutputBufferPtrs );++    if( bp->hostOutputChannels[0] )+        PaUtil_FreeMemory( bp->hostOutputChannels[0] );+}+++void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bp )+{+    unsigned long tempInputBufferSize, tempOutputBufferSize;++    bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer;+    bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer;++    if( bp->framesInTempInputBuffer > 0 )+    {+        tempInputBufferSize =+            bp->framesPerTempBuffer * bp->bytesPerUserInputSample * bp->inputChannelCount;+        memset( bp->tempInputBuffer, 0, tempInputBufferSize );+    }++    if( bp->framesInTempOutputBuffer > 0 )+    {      +        tempOutputBufferSize =+            bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * bp->outputChannelCount;+        memset( bp->tempOutputBuffer, 0, tempOutputBufferSize );+    }+}+++unsigned long PaUtil_GetBufferProcessorInputLatencyFrames( PaUtilBufferProcessor* bp )+{+    return bp->initialFramesInTempInputBuffer;+}+++unsigned long PaUtil_GetBufferProcessorOutputLatencyFrames( PaUtilBufferProcessor* bp )+{+    return bp->initialFramesInTempOutputBuffer;+}+++void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bp,+        unsigned long frameCount )+{+    if( frameCount == 0 )+        bp->hostInputFrameCount[0] = bp->framesPerHostBuffer;+    else+        bp->hostInputFrameCount[0] = frameCount;+}+        ++void PaUtil_SetNoInput( PaUtilBufferProcessor* bp )+{+    assert( bp->inputChannelCount > 0 );++    bp->hostInputChannels[0][0].data = 0;+}+++void PaUtil_SetInputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data, unsigned int stride )+{+    assert( channel < bp->inputChannelCount );+    +    bp->hostInputChannels[0][channel].data = data;+    bp->hostInputChannels[0][channel].stride = stride;+}+++void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bp,+        unsigned int firstChannel, void *data, unsigned int channelCount )+{+    unsigned int i;+    unsigned int channel = firstChannel;+    unsigned char *p = (unsigned char*)data;++    if( channelCount == 0 )+        channelCount = bp->inputChannelCount;++    assert( firstChannel < bp->inputChannelCount );+    assert( firstChannel + channelCount <= bp->inputChannelCount );+    assert( bp->hostInputIsInterleaved );++    for( i=0; i< channelCount; ++i )+    {+        bp->hostInputChannels[0][channel+i].data = p;+        p += bp->bytesPerHostInputSample;+        bp->hostInputChannels[0][channel+i].stride = channelCount;+    }+}+++void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data )+{+    assert( channel < bp->inputChannelCount );+    assert( !bp->hostInputIsInterleaved );+    +    bp->hostInputChannels[0][channel].data = data;+    bp->hostInputChannels[0][channel].stride = 1;+}+++void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bp,+        unsigned long frameCount )+{+    bp->hostInputFrameCount[1] = frameCount;+}+++void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data, unsigned int stride )+{+    assert( channel < bp->inputChannelCount );++    bp->hostInputChannels[1][channel].data = data;+    bp->hostInputChannels[1][channel].stride = stride;+}+++void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bp,+        unsigned int firstChannel, void *data, unsigned int channelCount )+{+    unsigned int i;+    unsigned int channel = firstChannel;+    unsigned char *p = (unsigned char*)data;++    if( channelCount == 0 )+        channelCount = bp->inputChannelCount;++    assert( firstChannel < bp->inputChannelCount );+    assert( firstChannel + channelCount <= bp->inputChannelCount );+    assert( bp->hostInputIsInterleaved );+    +    for( i=0; i< channelCount; ++i )+    {+        bp->hostInputChannels[1][channel+i].data = p;+        p += bp->bytesPerHostInputSample;+        bp->hostInputChannels[1][channel+i].stride = channelCount;+    }+}++        +void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data )+{+    assert( channel < bp->inputChannelCount );+    assert( !bp->hostInputIsInterleaved );+    +    bp->hostInputChannels[1][channel].data = data;+    bp->hostInputChannels[1][channel].stride = 1;+}+++void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bp,+        unsigned long frameCount )+{+    if( frameCount == 0 )+        bp->hostOutputFrameCount[0] = bp->framesPerHostBuffer;+    else+        bp->hostOutputFrameCount[0] = frameCount;+}+++void PaUtil_SetNoOutput( PaUtilBufferProcessor* bp )+{+    assert( bp->outputChannelCount > 0 );++    bp->hostOutputChannels[0][0].data = 0;++    /* note that only NonAdaptingProcess is able to deal with no output at this stage. not implemented for AdaptingProcess */+}+++void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data, unsigned int stride )+{+    assert( channel < bp->outputChannelCount );+    assert( data != NULL );++    bp->hostOutputChannels[0][channel].data = data;+    bp->hostOutputChannels[0][channel].stride = stride;+}+++void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bp,+        unsigned int firstChannel, void *data, unsigned int channelCount )+{+    unsigned int i;+    unsigned int channel = firstChannel;+    unsigned char *p = (unsigned char*)data;++    if( channelCount == 0 )+        channelCount = bp->outputChannelCount;++    assert( firstChannel < bp->outputChannelCount );+    assert( firstChannel + channelCount <= bp->outputChannelCount );+    assert( bp->hostOutputIsInterleaved );+    +    for( i=0; i< channelCount; ++i )+    {+        PaUtil_SetOutputChannel( bp, channel + i, p, channelCount );+        p += bp->bytesPerHostOutputSample;+    }+}+++void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data )+{+    assert( channel < bp->outputChannelCount );+    assert( !bp->hostOutputIsInterleaved );++    PaUtil_SetOutputChannel( bp, channel, data, 1 );+}+++void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bp,+        unsigned long frameCount )+{+    bp->hostOutputFrameCount[1] = frameCount;+}+++void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data, unsigned int stride )+{+    assert( channel < bp->outputChannelCount );+    assert( data != NULL );++    bp->hostOutputChannels[1][channel].data = data;+    bp->hostOutputChannels[1][channel].stride = stride;+}+++void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bp,+        unsigned int firstChannel, void *data, unsigned int channelCount )+{+    unsigned int i;+    unsigned int channel = firstChannel;+    unsigned char *p = (unsigned char*)data;++    if( channelCount == 0 )+        channelCount = bp->outputChannelCount;++    assert( firstChannel < bp->outputChannelCount );+    assert( firstChannel + channelCount <= bp->outputChannelCount );+    assert( bp->hostOutputIsInterleaved );+    +    for( i=0; i< channelCount; ++i )+    {+        PaUtil_Set2ndOutputChannel( bp, channel + i, p, channelCount );+        p += bp->bytesPerHostOutputSample;+    }+}++        +void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,+        unsigned int channel, void *data )+{+    assert( channel < bp->outputChannelCount );+    assert( !bp->hostOutputIsInterleaved );+    +    PaUtil_Set2ndOutputChannel( bp, channel, data, 1 );+}+++void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bp,+        PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags )+{+    bp->timeInfo = timeInfo;++    /* the first streamCallback will be called to process samples which are+        currently in the input buffer before the ones starting at the timeInfo time */+        +    bp->timeInfo->inputBufferAdcTime -= bp->framesInTempInputBuffer * bp->samplePeriod;+    +    /* We just pass through timeInfo->currentTime provided by the caller. This is+        not strictly conformant to the word of the spec, since the buffer processor +        might call the callback multiple times, and we never refresh currentTime. */++    /* the first streamCallback will be called to generate samples which will be+        outputted after the frames currently in the output buffer have been+        outputted. */+    bp->timeInfo->outputBufferDacTime += bp->framesInTempOutputBuffer * bp->samplePeriod;++    bp->callbackStatusFlags = callbackStatusFlags;++    bp->hostInputFrameCount[1] = 0;+    bp->hostOutputFrameCount[1] = 0;+}+++/*+    NonAdaptingProcess() is a simple buffer copying adaptor that can handle+    both full and half duplex copies. It processes framesToProcess frames,+    broken into blocks bp->framesPerTempBuffer long.+    This routine can be used when the streamCallback doesn't care what length+    the buffers are, or when framesToProcess is an integer multiple of+    bp->framesPerTempBuffer, in which case streamCallback will always be called+    with bp->framesPerTempBuffer samples.+*/+static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,+        int *streamCallbackResult,+        PaUtilChannelDescriptor *hostInputChannels,+        PaUtilChannelDescriptor *hostOutputChannels,+        unsigned long framesToProcess )+{+    void *userInput, *userOutput;+    unsigned char *srcBytePtr, *destBytePtr;+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */+    unsigned int i;+    unsigned long frameCount;+    unsigned long framesToGo = framesToProcess;+    unsigned long framesProcessed = 0;+    int skipOutputConvert = 0;+    int skipInputConvert = 0;+++    if( *streamCallbackResult == paContinue )+    {+        do+        {+            frameCount = PA_MIN_( bp->framesPerTempBuffer, framesToGo );++            /* configure user input buffer and convert input data (host -> user) */+            if( bp->inputChannelCount == 0 )+            {+                /* no input */+                userInput = 0;+            }+            else /* there are input channels */+            {+                +                destBytePtr = (unsigned char *)bp->tempInputBuffer;++                if( bp->userInputIsInterleaved )+                {+                    destSampleStrideSamples = bp->inputChannelCount;+                    destChannelStrideBytes = bp->bytesPerUserInputSample;++                    /* process host buffer directly, or use temp buffer if formats differ or host buffer non-interleaved,+                     * or if the number of channels differs between the host (set in stride) and the user */+                    if( bp->userInputSampleFormatIsEqualToHost && bp->hostInputIsInterleaved+                        && bp->hostInputChannels[0][0].data && bp->inputChannelCount == hostInputChannels[0].stride )+                    {+                        userInput = hostInputChannels[0].data;+                        destBytePtr = (unsigned char *)hostInputChannels[0].data;+                        skipInputConvert = 1;+                    }+                    else+                    {+                        userInput = bp->tempInputBuffer;+                    }+                }+                else /* user input is not interleaved */+                {+                    destSampleStrideSamples = 1;+                    destChannelStrideBytes = frameCount * bp->bytesPerUserInputSample;++                    /* setup non-interleaved ptrs */+                    if( bp->userInputSampleFormatIsEqualToHost && !bp->hostInputIsInterleaved && bp->hostInputChannels[0][0].data )+                    {+                        for( i=0; i<bp->inputChannelCount; ++i )+                        {+                            bp->tempInputBufferPtrs[i] = hostInputChannels[i].data;+                        }+                        skipInputConvert = 1;+                    }+                    else+                    {+                        for( i=0; i<bp->inputChannelCount; ++i )+                        {+                            bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) ++                                i * bp->bytesPerUserInputSample * frameCount;+                        }+                    }+                +                    userInput = bp->tempInputBufferPtrs;+                }++                if( !bp->hostInputChannels[0][0].data )+                {+                    /* no input was supplied (see PaUtil_SetNoInput), so+                        zero the input buffer */++                    for( i=0; i<bp->inputChannelCount; ++i )+                    {+                        bp->inputZeroer( destBytePtr, destSampleStrideSamples, frameCount );+                        destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */+                    }+                }+                else+	            {+                    if( skipInputConvert )+                    {+                        for( i=0; i<bp->inputChannelCount; ++i )+                        {+                            /* advance src ptr for next iteration */+                            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) ++                                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;+                        }+                    }+                    else+                    {+                        for( i=0; i<bp->inputChannelCount; ++i )+                        {+                            bp->inputConverter( destBytePtr, destSampleStrideSamples,+                                                    hostInputChannels[i].data,+                                                    hostInputChannels[i].stride,+                                                    frameCount, &bp->ditherGenerator );++                            destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */++                            /* advance src ptr for next iteration */+                            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) ++                                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;+                        }+                    }+                }+            }++            /* configure user output buffer */+            if( bp->outputChannelCount == 0 )+            {+                /* no output */+                userOutput = 0;+            }+            else /* there are output channels */+            {+                if( bp->userOutputIsInterleaved )+                {+                    /* process host buffer directly, or use temp buffer if formats differ or host buffer non-interleaved */+                    if( bp->userOutputSampleFormatIsEqualToHost && bp->hostOutputIsInterleaved )+                    {+                        userOutput = hostOutputChannels[0].data;+                        skipOutputConvert = 1;+                    }+                    else+                    {+                        userOutput = bp->tempOutputBuffer;+                    }+                }+                else /* user output is not interleaved */+                {+                    if( bp->userOutputSampleFormatIsEqualToHost && !bp->hostOutputIsInterleaved )+                    {+                        for( i=0; i<bp->outputChannelCount; ++i )+                        {+                            bp->tempOutputBufferPtrs[i] = hostOutputChannels[i].data;+                        }+                        skipOutputConvert = 1;+                    }+                    else+                    {+                        for( i=0; i<bp->outputChannelCount; ++i )+                        {+                            bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) ++                                i * bp->bytesPerUserOutputSample * frameCount;+                        }+                    }++                    userOutput = bp->tempOutputBufferPtrs;+                }+            }+        +            *streamCallbackResult = bp->streamCallback( userInput, userOutput,+                    frameCount, bp->timeInfo, bp->callbackStatusFlags, bp->userData );++            if( *streamCallbackResult == paAbort )+            {+                /* callback returned paAbort, don't advance framesProcessed+                        and framesToGo, they will be handled below */+            }+            else+            {+                bp->timeInfo->inputBufferAdcTime += frameCount * bp->samplePeriod;+                bp->timeInfo->outputBufferDacTime += frameCount * bp->samplePeriod;++                /* convert output data (user -> host) */+                +                if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data )+                {+                    if( skipOutputConvert )+					{+						for( i=0; i<bp->outputChannelCount; ++i )+                    	{+                        	/* advance dest ptr for next iteration */+                        	hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                            	    frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+                    	}+					}+					else+					{++                    	srcBytePtr = (unsigned char *)bp->tempOutputBuffer;++                    	if( bp->userOutputIsInterleaved )+                    	{+                        	srcSampleStrideSamples = bp->outputChannelCount;+                        	srcChannelStrideBytes = bp->bytesPerUserOutputSample;+                    	}+                    	else /* user output is not interleaved */+                    	{+                        	srcSampleStrideSamples = 1;+                        	srcChannelStrideBytes = frameCount * bp->bytesPerUserOutputSample;+                    	}++                    	for( i=0; i<bp->outputChannelCount; ++i )+                    	{+                        	bp->outputConverter(    hostOutputChannels[i].data,+                                                	hostOutputChannels[i].stride,+                                                	srcBytePtr, srcSampleStrideSamples,+                                                	frameCount, &bp->ditherGenerator );++                        	srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */++                        	/* advance dest ptr for next iteration */+                        	hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                                		frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+                    	}+					}+                }+             +                framesProcessed += frameCount;++                framesToGo -= frameCount;+            }+        }+        while( framesToGo > 0  && *streamCallbackResult == paContinue );+    }++    if( framesToGo > 0 )+    {+        /* zero any remaining frames output. There will only be remaining frames+            if the callback has returned paComplete or paAbort */++        frameCount = framesToGo;++        if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data )+        {+            for( i=0; i<bp->outputChannelCount; ++i )+            {+                bp->outputZeroer(   hostOutputChannels[i].data,+                                    hostOutputChannels[i].stride,+                                    frameCount );++                /* advance dest ptr for next iteration */+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+            }+        }++        framesProcessed += frameCount;+    }++    return framesProcessed;+}+++/*+    AdaptingInputOnlyProcess() is a half duplex input buffer processor. It+    converts data from the input buffers into the temporary input buffer,+    when the temporary input buffer is full, it calls the streamCallback.+*/+static unsigned long AdaptingInputOnlyProcess( PaUtilBufferProcessor *bp,+        int *streamCallbackResult,+        PaUtilChannelDescriptor *hostInputChannels,+        unsigned long framesToProcess )+{+    void *userInput, *userOutput;+    unsigned char *destBytePtr;+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */+    unsigned int i;+    unsigned long frameCount;+    unsigned long framesToGo = framesToProcess;+    unsigned long framesProcessed = 0;+    +    userOutput = 0;++    do+    {+        frameCount = ( bp->framesInTempInputBuffer + framesToGo > bp->framesPerUserBuffer )+                ? ( bp->framesPerUserBuffer - bp->framesInTempInputBuffer )+                : framesToGo;++        /* convert frameCount samples into temp buffer */++        if( bp->userInputIsInterleaved )+        {+            destBytePtr = ((unsigned char*)bp->tempInputBuffer) ++                    bp->bytesPerUserInputSample * bp->inputChannelCount *+                    bp->framesInTempInputBuffer;+                      +            destSampleStrideSamples = bp->inputChannelCount;+            destChannelStrideBytes = bp->bytesPerUserInputSample;++            userInput = bp->tempInputBuffer;+        }+        else /* user input is not interleaved */+        {+            destBytePtr = ((unsigned char*)bp->tempInputBuffer) ++                    bp->bytesPerUserInputSample * bp->framesInTempInputBuffer;++            destSampleStrideSamples = 1;+            destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample;++            /* setup non-interleaved ptrs */+            for( i=0; i<bp->inputChannelCount; ++i )+            {+                bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) ++                    i * bp->bytesPerUserInputSample * bp->framesPerUserBuffer;+            }+                    +            userInput = bp->tempInputBufferPtrs;+        }++        for( i=0; i<bp->inputChannelCount; ++i )+        {+            bp->inputConverter( destBytePtr, destSampleStrideSamples,+                                    hostInputChannels[i].data,+                                    hostInputChannels[i].stride,+                                    frameCount, &bp->ditherGenerator );++            destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */++            /* advance src ptr for next iteration */+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) ++                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;+        }++        bp->framesInTempInputBuffer += frameCount;++        if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer )+        {+            /**+            @todo (non-critical optimisation)+            The conditional below implements the continue/complete/abort mechanism+            simply by continuing on iterating through the input buffer, but not+            passing the data to the callback. With care, the outer loop could be+            terminated earlier, thus some unneeded conversion cycles would be+            saved.+            */+            if( *streamCallbackResult == paContinue )+            {+                bp->timeInfo->outputBufferDacTime = 0;++                *streamCallbackResult = bp->streamCallback( userInput, userOutput,+                        bp->framesPerUserBuffer, bp->timeInfo,+                        bp->callbackStatusFlags, bp->userData );++                bp->timeInfo->inputBufferAdcTime += bp->framesPerUserBuffer * bp->samplePeriod;+            }+            +            bp->framesInTempInputBuffer = 0;+        }++        framesProcessed += frameCount;++        framesToGo -= frameCount;+    }while( framesToGo > 0 );++    return framesProcessed;+}+++/*+    AdaptingOutputOnlyProcess() is a half duplex output buffer processor.+    It converts data from the temporary output buffer, to the output buffers,+    when the temporary output buffer is empty, it calls the streamCallback.+*/+static unsigned long AdaptingOutputOnlyProcess( PaUtilBufferProcessor *bp,+        int *streamCallbackResult,+        PaUtilChannelDescriptor *hostOutputChannels,+        unsigned long framesToProcess )+{+    void *userInput, *userOutput;+    unsigned char *srcBytePtr;+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int srcChannelStrideBytes;  /* stride from one channel to the next, in bytes */+    unsigned int i;+    unsigned long frameCount;+    unsigned long framesToGo = framesToProcess;+    unsigned long framesProcessed = 0;++    do+    {+        if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult == paContinue )+        {+            userInput = 0;++            /* setup userOutput */+            if( bp->userOutputIsInterleaved )+            {+                userOutput = bp->tempOutputBuffer;+            }+            else /* user output is not interleaved */+            {+                for( i = 0; i < bp->outputChannelCount; ++i )+                {+                    bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) ++                            i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;+                }++                userOutput = bp->tempOutputBufferPtrs;+            }++            bp->timeInfo->inputBufferAdcTime = 0;+            +            *streamCallbackResult = bp->streamCallback( userInput, userOutput,+                    bp->framesPerUserBuffer, bp->timeInfo,+                    bp->callbackStatusFlags, bp->userData );++            if( *streamCallbackResult == paAbort )+            {+                /* if the callback returned paAbort, we disregard its output */+            }+            else+            {+                bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod;++                bp->framesInTempOutputBuffer = bp->framesPerUserBuffer;+            }+        }++        if( bp->framesInTempOutputBuffer > 0 )+        {+            /* convert frameCount frames from user buffer to host buffer */++            frameCount = PA_MIN_( bp->framesInTempOutputBuffer, framesToGo );++            if( bp->userOutputIsInterleaved )+            {+                srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) ++                        bp->bytesPerUserOutputSample * bp->outputChannelCount *+                        (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);++                srcSampleStrideSamples = bp->outputChannelCount;+                srcChannelStrideBytes = bp->bytesPerUserOutputSample;+            }+            else /* user output is not interleaved */+            {+                srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) ++                        bp->bytesPerUserOutputSample *+                        (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);+                            +                srcSampleStrideSamples = 1;+                srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;+            }++            for( i=0; i<bp->outputChannelCount; ++i )+            {+                bp->outputConverter(    hostOutputChannels[i].data,+                                        hostOutputChannels[i].stride,+                                        srcBytePtr, srcSampleStrideSamples,+                                        frameCount, &bp->ditherGenerator );++                srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */++                /* advance dest ptr for next iteration */+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+            }++            bp->framesInTempOutputBuffer -= frameCount;+        }+        else+        {+            /* no more user data is available because the callback has returned+                paComplete or paAbort. Fill the remainder of the host buffer+                with zeros.+            */++            frameCount = framesToGo;++            for( i=0; i<bp->outputChannelCount; ++i )+            {+                bp->outputZeroer(   hostOutputChannels[i].data,+                                    hostOutputChannels[i].stride,+                                    frameCount );++                /* advance dest ptr for next iteration */+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+            }+        }+        +        framesProcessed += frameCount;+        +        framesToGo -= frameCount;++    }while( framesToGo > 0 );++    return framesProcessed;+}++/* CopyTempOutputBuffersToHostOutputBuffers is called from AdaptingProcess to copy frames from+	tempOutputBuffer to hostOutputChannels. This includes data conversion+	and interleaving. +*/+static void CopyTempOutputBuffersToHostOutputBuffers( PaUtilBufferProcessor *bp)+{+    unsigned long maxFramesToCopy;+    PaUtilChannelDescriptor *hostOutputChannels;+    unsigned int frameCount;+    unsigned char *srcBytePtr;+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */+    unsigned int i;++     /* copy frames from user to host output buffers */+     while( bp->framesInTempOutputBuffer > 0 &&+             ((bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) > 0) )+     {+         maxFramesToCopy = bp->framesInTempOutputBuffer;++         /* select the output buffer set (1st or 2nd) */+         if( bp->hostOutputFrameCount[0] > 0 )+         {+             hostOutputChannels = bp->hostOutputChannels[0];+             frameCount = PA_MIN_( bp->hostOutputFrameCount[0], maxFramesToCopy );+         }+         else+         {+             hostOutputChannels = bp->hostOutputChannels[1];+             frameCount = PA_MIN_( bp->hostOutputFrameCount[1], maxFramesToCopy );+         }++         if( bp->userOutputIsInterleaved )+         {+             srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) ++                     bp->bytesPerUserOutputSample * bp->outputChannelCount *+                     (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);+                         +             srcSampleStrideSamples = bp->outputChannelCount;+             srcChannelStrideBytes = bp->bytesPerUserOutputSample;+         }+         else /* user output is not interleaved */+         {+             srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) ++                     bp->bytesPerUserOutputSample *+                     (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);++             srcSampleStrideSamples = 1;+             srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;+         }++         for( i=0; i<bp->outputChannelCount; ++i )+         {+             assert( hostOutputChannels[i].data != NULL );+             bp->outputConverter(    hostOutputChannels[i].data,+                                     hostOutputChannels[i].stride,+                                     srcBytePtr, srcSampleStrideSamples,+                                     frameCount, &bp->ditherGenerator );++             srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */++             /* advance dest ptr for next iteration */+             hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                     frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+         }++         if( bp->hostOutputFrameCount[0] > 0 )+             bp->hostOutputFrameCount[0] -= frameCount;+         else+             bp->hostOutputFrameCount[1] -= frameCount;++         bp->framesInTempOutputBuffer -= frameCount;+     }+}++/*+    AdaptingProcess is a full duplex adapting buffer processor. It converts+    data from the temporary output buffer into the host output buffers, then+    from the host input buffers into the temporary input buffers. Calling the+    streamCallback when necessary.+    When processPartialUserBuffers is 0, all available input data will be+    consumed and all available output space will be filled. When+    processPartialUserBuffers is non-zero, as many full user buffers+    as possible will be processed, but partial buffers will not be consumed.+*/+static unsigned long AdaptingProcess( PaUtilBufferProcessor *bp,+        int *streamCallbackResult, int processPartialUserBuffers )+{+    void *userInput, *userOutput;+    unsigned long framesProcessed = 0;+    unsigned long framesAvailable;+    unsigned long endProcessingMinFrameCount;+    unsigned long maxFramesToCopy;+    PaUtilChannelDescriptor *hostInputChannels, *hostOutputChannels;+    unsigned int frameCount;+    unsigned char *destBytePtr;+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */+    unsigned int i, j;+ ++    framesAvailable = bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1];/* this is assumed to be the same as the output buffer's frame count */++    if( processPartialUserBuffers )+        endProcessingMinFrameCount = 0;+    else+        endProcessingMinFrameCount = (bp->framesPerUserBuffer - 1);++    /* Fill host output with remaining frames in user output (tempOutputBuffer) */+    CopyTempOutputBuffersToHostOutputBuffers( bp );		  	++    while( framesAvailable > endProcessingMinFrameCount ) +    {++        if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult != paContinue )+        {+            /* the callback will not be called any more, so zero what remains+                of the host output buffers */++            for( i=0; i<2; ++i )+            {+                frameCount = bp->hostOutputFrameCount[i];+                if( frameCount > 0 )+                {+                    hostOutputChannels = bp->hostOutputChannels[i];+                    +                    for( j=0; j<bp->outputChannelCount; ++j )+                    {+                        bp->outputZeroer(   hostOutputChannels[j].data,+                                            hostOutputChannels[j].stride,+                                            frameCount );++                        /* advance dest ptr for next iteration  */+                        hostOutputChannels[j].data = ((unsigned char*)hostOutputChannels[j].data) ++                                frameCount * hostOutputChannels[j].stride * bp->bytesPerHostOutputSample;+                    }+                    bp->hostOutputFrameCount[i] = 0;+                }+            }+        }          +++        /* copy frames from host to user input buffers */+        while( bp->framesInTempInputBuffer < bp->framesPerUserBuffer &&+                ((bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) > 0) )+        {+            maxFramesToCopy = bp->framesPerUserBuffer - bp->framesInTempInputBuffer;++            /* select the input buffer set (1st or 2nd) */+            if( bp->hostInputFrameCount[0] > 0 )+            {+                hostInputChannels = bp->hostInputChannels[0];+                frameCount = PA_MIN_( bp->hostInputFrameCount[0], maxFramesToCopy );+            }+            else+            {+                hostInputChannels = bp->hostInputChannels[1];+                frameCount = PA_MIN_( bp->hostInputFrameCount[1], maxFramesToCopy );+            }++            /* configure conversion destination pointers */+            if( bp->userInputIsInterleaved )+            {+                destBytePtr = ((unsigned char*)bp->tempInputBuffer) ++                        bp->bytesPerUserInputSample * bp->inputChannelCount *+                        bp->framesInTempInputBuffer;++                destSampleStrideSamples = bp->inputChannelCount;+                destChannelStrideBytes = bp->bytesPerUserInputSample;+            }+            else /* user input is not interleaved */+            {+                destBytePtr = ((unsigned char*)bp->tempInputBuffer) ++                        bp->bytesPerUserInputSample * bp->framesInTempInputBuffer;++                destSampleStrideSamples = 1;+                destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample;+            }++            for( i=0; i<bp->inputChannelCount; ++i )+            {+                bp->inputConverter( destBytePtr, destSampleStrideSamples,+                                        hostInputChannels[i].data,+                                        hostInputChannels[i].stride,+                                        frameCount, &bp->ditherGenerator );++                destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */++                /* advance src ptr for next iteration */+                hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) ++                        frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;+            }++            if( bp->hostInputFrameCount[0] > 0 )+                bp->hostInputFrameCount[0] -= frameCount;+            else+                bp->hostInputFrameCount[1] -= frameCount;+                +            bp->framesInTempInputBuffer += frameCount;++            /* update framesAvailable and framesProcessed based on input consumed+                unless something is very wrong this will also correspond to the+                amount of output generated */+            framesAvailable -= frameCount;+            framesProcessed += frameCount;+        }++        /* call streamCallback */+        if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer &&+            bp->framesInTempOutputBuffer == 0 )+        {+            if( *streamCallbackResult == paContinue )+            {+                /* setup userInput */+                if( bp->userInputIsInterleaved )+                {+                    userInput = bp->tempInputBuffer;+                }+                else /* user input is not interleaved */+                {+                    for( i = 0; i < bp->inputChannelCount; ++i )+                    {+                        bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) ++                                i * bp->framesPerUserBuffer * bp->bytesPerUserInputSample;+                    }++                    userInput = bp->tempInputBufferPtrs;+                }++                /* setup userOutput */+                if( bp->userOutputIsInterleaved )+                {+                    userOutput = bp->tempOutputBuffer;+                }+                else /* user output is not interleaved */+                {+                    for( i = 0; i < bp->outputChannelCount; ++i )+                    {+                        bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) ++                                i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;+                    }++                    userOutput = bp->tempOutputBufferPtrs;+                }++                /* call streamCallback */++                *streamCallbackResult = bp->streamCallback( userInput, userOutput,+                        bp->framesPerUserBuffer, bp->timeInfo,+                        bp->callbackStatusFlags, bp->userData );++                bp->timeInfo->inputBufferAdcTime += bp->framesPerUserBuffer * bp->samplePeriod;+                bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod;++                bp->framesInTempInputBuffer = 0;++                if( *streamCallbackResult == paAbort )+                    bp->framesInTempOutputBuffer = 0;+                else+                    bp->framesInTempOutputBuffer = bp->framesPerUserBuffer;+            }+            else+            {+                /* paComplete or paAbort has already been called. */++                bp->framesInTempInputBuffer = 0;+            }+        }++        /* copy frames from user (tempOutputBuffer) to host output buffers (hostOutputChannels) +           Means to process the user output provided by the callback. Has to be called after+            each callback. */+        CopyTempOutputBuffersToHostOutputBuffers( bp );		  	++    }+    +    return framesProcessed;+}+++unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bp, int *streamCallbackResult )+{+    unsigned long framesToProcess, framesToGo;+    unsigned long framesProcessed = 0;+    +    if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0+            && bp->hostInputChannels[0][0].data /* input was supplied (see PaUtil_SetNoInput) */+            && bp->hostOutputChannels[0][0].data /* output was supplied (see PaUtil_SetNoOutput) */ )+    {+        assert( (bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) ==+                (bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) );+    }++    assert( *streamCallbackResult == paContinue+            || *streamCallbackResult == paComplete+            || *streamCallbackResult == paAbort ); /* don't forget to pass in a valid callback result value */++    if( bp->useNonAdaptingProcess )+    {+        if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 )+        {+            /* full duplex non-adapting process, splice buffers if they are+                different lengths */++            framesToGo = bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]; /* relies on assert above for input/output equivalence */++            do{+                unsigned long noInputInputFrameCount;+                unsigned long *hostInputFrameCount;+                PaUtilChannelDescriptor *hostInputChannels;+                unsigned long noOutputOutputFrameCount;+                unsigned long *hostOutputFrameCount;+                PaUtilChannelDescriptor *hostOutputChannels;+                unsigned long framesProcessedThisIteration;++                if( !bp->hostInputChannels[0][0].data )+                {+                    /* no input was supplied (see PaUtil_SetNoInput)+                        NonAdaptingProcess knows how to deal with this+                    */+                    noInputInputFrameCount = framesToGo;+                    hostInputFrameCount = &noInputInputFrameCount;+                    hostInputChannels = 0;+                }+                else if( bp->hostInputFrameCount[0] != 0 )+                {+                    hostInputFrameCount = &bp->hostInputFrameCount[0];+                    hostInputChannels = bp->hostInputChannels[0];+                }+                else+                {+                    hostInputFrameCount = &bp->hostInputFrameCount[1];+                    hostInputChannels = bp->hostInputChannels[1];+                }++                if( !bp->hostOutputChannels[0][0].data )+                {+                    /* no output was supplied (see PaUtil_SetNoOutput)+                        NonAdaptingProcess knows how to deal with this+                    */+                    noOutputOutputFrameCount = framesToGo;+                    hostOutputFrameCount = &noOutputOutputFrameCount;+                    hostOutputChannels = 0;+                }+                if( bp->hostOutputFrameCount[0] != 0 )+                {+                    hostOutputFrameCount = &bp->hostOutputFrameCount[0];+                    hostOutputChannels = bp->hostOutputChannels[0];+                }+                else+                {+                    hostOutputFrameCount = &bp->hostOutputFrameCount[1];+                    hostOutputChannels = bp->hostOutputChannels[1];+                }++                framesToProcess = PA_MIN_( *hostInputFrameCount,+                                       *hostOutputFrameCount );++                assert( framesToProcess != 0 );+                +                framesProcessedThisIteration = NonAdaptingProcess( bp, streamCallbackResult,+                        hostInputChannels, hostOutputChannels,+                        framesToProcess );                                       ++                *hostInputFrameCount -= framesProcessedThisIteration;+                *hostOutputFrameCount -= framesProcessedThisIteration;++                framesProcessed += framesProcessedThisIteration;+                framesToGo -= framesProcessedThisIteration;+                +            }while( framesToGo > 0 );+        }+        else+        {+            /* half duplex non-adapting process, just process 1st and 2nd buffer */+            /* process first buffer */++            framesToProcess = (bp->inputChannelCount != 0)+                            ? bp->hostInputFrameCount[0]+                            : bp->hostOutputFrameCount[0];++            framesProcessed = NonAdaptingProcess( bp, streamCallbackResult,+                        bp->hostInputChannels[0], bp->hostOutputChannels[0],+                        framesToProcess );++            /* process second buffer if provided */+    +            framesToProcess = (bp->inputChannelCount != 0)+                            ? bp->hostInputFrameCount[1]+                            : bp->hostOutputFrameCount[1];+            if( framesToProcess > 0 )+            {+                framesProcessed += NonAdaptingProcess( bp, streamCallbackResult,+                    bp->hostInputChannels[1], bp->hostOutputChannels[1],+                    framesToProcess );+            }+        }+    }+    else /* block adaption necessary*/+    {++        if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 )+        {+            /* full duplex */+            +            if( bp->hostBufferSizeMode == paUtilVariableHostBufferSizePartialUsageAllowed  )+            {+                framesProcessed = AdaptingProcess( bp, streamCallbackResult,+                        0 /* dont process partial user buffers */ );+            }+            else+            {+                framesProcessed = AdaptingProcess( bp, streamCallbackResult,+                        1 /* process partial user buffers */ );+            }+        }+        else if( bp->inputChannelCount != 0 )+        {+            /* input only */+            framesToProcess = bp->hostInputFrameCount[0];++            framesProcessed = AdaptingInputOnlyProcess( bp, streamCallbackResult,+                        bp->hostInputChannels[0], framesToProcess );++            framesToProcess = bp->hostInputFrameCount[1];+            if( framesToProcess > 0 )+            {+                framesProcessed += AdaptingInputOnlyProcess( bp, streamCallbackResult,+                        bp->hostInputChannels[1], framesToProcess );+            }+        }+        else+        {+            /* output only */+            framesToProcess = bp->hostOutputFrameCount[0];++            framesProcessed = AdaptingOutputOnlyProcess( bp, streamCallbackResult,+                        bp->hostOutputChannels[0], framesToProcess );++            framesToProcess = bp->hostOutputFrameCount[1];+            if( framesToProcess > 0 )+            {+                framesProcessed += AdaptingOutputOnlyProcess( bp, streamCallbackResult,+                        bp->hostOutputChannels[1], framesToProcess );+            }+        }+    }++    return framesProcessed;+}+++int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bp )+{+    return (bp->framesInTempOutputBuffer) ? 0 : 1;+} +++unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bp,+        void **buffer, unsigned long frameCount )+{+    PaUtilChannelDescriptor *hostInputChannels;+    unsigned int framesToCopy;+    unsigned char *destBytePtr;+    void **nonInterleavedDestPtrs;+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */+    unsigned int i;++    hostInputChannels = bp->hostInputChannels[0];+    framesToCopy = PA_MIN_( bp->hostInputFrameCount[0], frameCount );++    if( bp->userInputIsInterleaved )+    {+        destBytePtr = (unsigned char*)*buffer;+        +        destSampleStrideSamples = bp->inputChannelCount;+        destChannelStrideBytes = bp->bytesPerUserInputSample;++        for( i=0; i<bp->inputChannelCount; ++i )+        {+            bp->inputConverter( destBytePtr, destSampleStrideSamples,+                                hostInputChannels[i].data,+                                hostInputChannels[i].stride,+                                framesToCopy, &bp->ditherGenerator );++            destBytePtr += destChannelStrideBytes;  /* skip to next dest channel */++            /* advance source ptr for next iteration */+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) ++                    framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample;+        }++        /* advance callers dest pointer (buffer) */+        *buffer = ((unsigned char *)*buffer) ++                framesToCopy * bp->inputChannelCount * bp->bytesPerUserInputSample;+    }+    else+    {+        /* user input is not interleaved */+        +        nonInterleavedDestPtrs = (void**)*buffer;++        destSampleStrideSamples = 1;+        +        for( i=0; i<bp->inputChannelCount; ++i )+        {+            destBytePtr = (unsigned char*)nonInterleavedDestPtrs[i];++            bp->inputConverter( destBytePtr, destSampleStrideSamples,+                                hostInputChannels[i].data,+                                hostInputChannels[i].stride,+                                framesToCopy, &bp->ditherGenerator );++            /* advance callers dest pointer (nonInterleavedDestPtrs[i]) */+            destBytePtr += bp->bytesPerUserInputSample * framesToCopy;+            nonInterleavedDestPtrs[i] = destBytePtr;+            +            /* advance source ptr for next iteration */+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) ++                    framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample;+        }+    }++    bp->hostInputFrameCount[0] -= framesToCopy;+    +    return framesToCopy;+}++unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bp,+        const void ** buffer, unsigned long frameCount )+{+    PaUtilChannelDescriptor *hostOutputChannels;+    unsigned int framesToCopy;+    unsigned char *srcBytePtr;+    void **nonInterleavedSrcPtrs;+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */+    unsigned int i;++    hostOutputChannels = bp->hostOutputChannels[0];+    framesToCopy = PA_MIN_( bp->hostOutputFrameCount[0], frameCount );++    if( bp->userOutputIsInterleaved )+    {+        srcBytePtr = (unsigned char*)*buffer;+        +        srcSampleStrideSamples = bp->outputChannelCount;+        srcChannelStrideBytes = bp->bytesPerUserOutputSample;++        for( i=0; i<bp->outputChannelCount; ++i )+        {+            bp->outputConverter(    hostOutputChannels[i].data,+                                    hostOutputChannels[i].stride,+                                    srcBytePtr, srcSampleStrideSamples,+                                    framesToCopy, &bp->ditherGenerator );++            srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */++            /* advance dest ptr for next iteration */+            hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                    framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+        }++        /* advance callers source pointer (buffer) */+        *buffer = ((unsigned char *)*buffer) ++                framesToCopy * bp->outputChannelCount * bp->bytesPerUserOutputSample;++    }+    else+    {+        /* user output is not interleaved */+        +        nonInterleavedSrcPtrs = (void**)*buffer;++        srcSampleStrideSamples = 1;+        +        for( i=0; i<bp->outputChannelCount; ++i )+        {+            srcBytePtr = (unsigned char*)nonInterleavedSrcPtrs[i];+            +            bp->outputConverter(    hostOutputChannels[i].data,+                                    hostOutputChannels[i].stride,+                                    srcBytePtr, srcSampleStrideSamples,+                                    framesToCopy, &bp->ditherGenerator );+++            /* advance callers source pointer (nonInterleavedSrcPtrs[i]) */+            srcBytePtr += bp->bytesPerUserOutputSample * framesToCopy;+            nonInterleavedSrcPtrs[i] = srcBytePtr;+            +            /* advance dest ptr for next iteration */+            hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                    framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+        }+    }++    bp->hostOutputFrameCount[0] += framesToCopy;+    +    return framesToCopy;+}+++unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bp, unsigned long frameCount )+{+    PaUtilChannelDescriptor *hostOutputChannels;+    unsigned int framesToZero;+    unsigned int i;++    hostOutputChannels = bp->hostOutputChannels[0];+    framesToZero = PA_MIN_( bp->hostOutputFrameCount[0], frameCount );++    for( i=0; i<bp->outputChannelCount; ++i )+    {+        bp->outputZeroer(   hostOutputChannels[i].data,+                            hostOutputChannels[i].stride,+                            framesToZero );+++        /* advance dest ptr for next iteration */+        hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) ++                framesToZero * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;+    }++    bp->hostOutputFrameCount[0] += framesToZero;+    +    return framesToZero;+}
+ portaudio/src/common/pa_ringbuffer.c view
@@ -0,0 +1,237 @@+/*+ * $Id: pa_ringbuffer.c 1738 2011-08-18 11:47:28Z rossb $+ * Portable Audio I/O Library+ * Ring Buffer utility.+ *+ * Author: Phil Burk, http://www.softsynth.com+ * modified for SMP safety on Mac OS X by Bjorn Roche+ * modified for SMP safety on Linux by Leland Lucius+ * also, allowed for const where possible+ * modified for multiple-byte-sized data elements by Sven Fischer + *+ * Note that this is safe only for a single-thread reader and a+ * single-thread writer.+ *+ * This program uses the PortAudio Portable Audio Library.+ * For more information see: http://www.portaudio.com+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/**+ @file+ @ingroup common_src+*/++#include <stdio.h>+#include <stdlib.h>+#include <math.h>+#include "pa_ringbuffer.h"+#include <string.h>+#include "pa_memorybarrier.h"++/***************************************************************************+ * Initialize FIFO.+ * elementCount must be power of 2, returns -1 if not.+ */+ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementSizeBytes, ring_buffer_size_t elementCount, void *dataPtr )+{+    if( ((elementCount-1) & elementCount) != 0) return -1; /* Not Power of two. */+    rbuf->bufferSize = elementCount;+    rbuf->buffer = (char *)dataPtr;+    PaUtil_FlushRingBuffer( rbuf );+    rbuf->bigMask = (elementCount*2)-1;+    rbuf->smallMask = (elementCount)-1;+    rbuf->elementSizeBytes = elementSizeBytes;+    return 0;+}++/***************************************************************************+** Return number of elements available for reading. */+ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( const PaUtilRingBuffer *rbuf )+{+    return ( (rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask );+}+/***************************************************************************+** Return number of elements available for writing. */+ring_buffer_size_t PaUtil_GetRingBufferWriteAvailable( const PaUtilRingBuffer *rbuf )+{+    return ( rbuf->bufferSize - PaUtil_GetRingBufferReadAvailable(rbuf));+}++/***************************************************************************+** Clear buffer. Should only be called when buffer is NOT being read or written. */+void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf )+{+    rbuf->writeIndex = rbuf->readIndex = 0;+}++/***************************************************************************+** Get address of region(s) to which we can write data.+** If the region is contiguous, size2 will be zero.+** If non-contiguous, size2 will be the size of second region.+** Returns room available to be written or elementCount, whichever is smaller.+*/+ring_buffer_size_t PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,+                                       void **dataPtr1, ring_buffer_size_t *sizePtr1,+                                       void **dataPtr2, ring_buffer_size_t *sizePtr2 )+{+    ring_buffer_size_t   index;+    ring_buffer_size_t   available = PaUtil_GetRingBufferWriteAvailable( rbuf );+    if( elementCount > available ) elementCount = available;+    /* Check to see if write is not contiguous. */+    index = rbuf->writeIndex & rbuf->smallMask;+    if( (index + elementCount) > rbuf->bufferSize )+    {+        /* Write data in two blocks that wrap the buffer. */+        ring_buffer_size_t   firstHalf = rbuf->bufferSize - index;+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];+        *sizePtr1 = firstHalf;+        *dataPtr2 = &rbuf->buffer[0];+        *sizePtr2 = elementCount - firstHalf;+    }+    else+    {+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];+        *sizePtr1 = elementCount;+        *dataPtr2 = NULL;+        *sizePtr2 = 0;+    }++    if( available )+        PaUtil_FullMemoryBarrier(); /* (write-after-read) => full barrier */++    return elementCount;+}+++/***************************************************************************+*/+ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )+{+    /* ensure that previous writes are seen before we update the write index +       (write after write)+    */+    PaUtil_WriteMemoryBarrier();+    return rbuf->writeIndex = (rbuf->writeIndex + elementCount) & rbuf->bigMask;+}++/***************************************************************************+** Get address of region(s) from which we can read data.+** If the region is contiguous, size2 will be zero.+** If non-contiguous, size2 will be the size of second region.+** Returns room available to be read or elementCount, whichever is smaller.+*/+ring_buffer_size_t PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,+                                void **dataPtr1, ring_buffer_size_t *sizePtr1,+                                void **dataPtr2, ring_buffer_size_t *sizePtr2 )+{+    ring_buffer_size_t   index;+    ring_buffer_size_t   available = PaUtil_GetRingBufferReadAvailable( rbuf ); /* doesn't use memory barrier */+    if( elementCount > available ) elementCount = available;+    /* Check to see if read is not contiguous. */+    index = rbuf->readIndex & rbuf->smallMask;+    if( (index + elementCount) > rbuf->bufferSize )+    {+        /* Write data in two blocks that wrap the buffer. */+        ring_buffer_size_t firstHalf = rbuf->bufferSize - index;+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];+        *sizePtr1 = firstHalf;+        *dataPtr2 = &rbuf->buffer[0];+        *sizePtr2 = elementCount - firstHalf;+    }+    else+    {+        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];+        *sizePtr1 = elementCount;+        *dataPtr2 = NULL;+        *sizePtr2 = 0;+    }+    +    if( available )+        PaUtil_ReadMemoryBarrier(); /* (read-after-read) => read barrier */++    return elementCount;+}+/***************************************************************************+*/+ring_buffer_size_t PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )+{+    /* ensure that previous reads (copies out of the ring buffer) are always completed before updating (writing) the read index. +       (write-after-read) => full barrier+    */+    PaUtil_FullMemoryBarrier();+    return rbuf->readIndex = (rbuf->readIndex + elementCount) & rbuf->bigMask;+}++/***************************************************************************+** Return elements written. */+ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, ring_buffer_size_t elementCount )+{+    ring_buffer_size_t size1, size2, numWritten;+    void *data1, *data2;+    numWritten = PaUtil_GetRingBufferWriteRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );+    if( size2 > 0 )+    {++        memcpy( data1, data, size1*rbuf->elementSizeBytes );+        data = ((char *)data) + size1*rbuf->elementSizeBytes;+        memcpy( data2, data, size2*rbuf->elementSizeBytes );+    }+    else+    {+        memcpy( data1, data, size1*rbuf->elementSizeBytes );+    }+    PaUtil_AdvanceRingBufferWriteIndex( rbuf, numWritten );+    return numWritten;+}++/***************************************************************************+** Return elements read. */+ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ring_buffer_size_t elementCount )+{+    ring_buffer_size_t size1, size2, numRead;+    void *data1, *data2;+    numRead = PaUtil_GetRingBufferReadRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );+    if( size2 > 0 )+    {+        memcpy( data, data1, size1*rbuf->elementSizeBytes );+        data = ((char *)data) + size1*rbuf->elementSizeBytes;+        memcpy( data, data2, size2*rbuf->elementSizeBytes );+    }+    else+    {+        memcpy( data, data1, size1*rbuf->elementSizeBytes );+    }+    PaUtil_AdvanceRingBufferReadIndex( rbuf, numRead );+    return numRead;+}
+ portaudio/src/common/pa_stream.c view
@@ -0,0 +1,150 @@+/*+ * $Id: pa_stream.c 1339 2008-02-15 07:50:33Z rossb $+ * Portable Audio I/O Library+ * stream interface+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 2008 Ross Bencina+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Stream interfaces, representation structures and helper functions+ used to interface between pa_front.c host API implementations.+*/+++#include "pa_stream.h"+++void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface,+                                       PaError (*Close)( PaStream* ),+                                       PaError (*Start)( PaStream* ),+                                       PaError (*Stop)( PaStream* ),+                                       PaError (*Abort)( PaStream* ),+                                       PaError (*IsStopped)( PaStream* ),+                                       PaError (*IsActive)( PaStream* ),+                                       PaTime (*GetTime)( PaStream* ),+                                       double (*GetCpuLoad)( PaStream* ),+                                       PaError (*Read)( PaStream*, void *, unsigned long ),+                                       PaError (*Write)( PaStream*, const void *, unsigned long ),+                                       signed long (*GetReadAvailable)( PaStream* ),+                                       signed long (*GetWriteAvailable)( PaStream* )  )+{+    streamInterface->Close = Close;+    streamInterface->Start = Start;+    streamInterface->Stop = Stop;+    streamInterface->Abort = Abort;+    streamInterface->IsStopped = IsStopped;+    streamInterface->IsActive = IsActive;+    streamInterface->GetTime = GetTime;+    streamInterface->GetCpuLoad = GetCpuLoad;+    streamInterface->Read = Read;+    streamInterface->Write = Write;+    streamInterface->GetReadAvailable = GetReadAvailable;+    streamInterface->GetWriteAvailable = GetWriteAvailable;+}+++void PaUtil_InitializeStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation,+        PaUtilStreamInterface *streamInterface,+        PaStreamCallback *streamCallback,+        void *userData )+{+    streamRepresentation->magic = PA_STREAM_MAGIC;+    streamRepresentation->nextOpenStream = 0;+    streamRepresentation->streamInterface = streamInterface;+    streamRepresentation->streamCallback = streamCallback;+    streamRepresentation->streamFinishedCallback = 0;++    streamRepresentation->userData = userData;++    streamRepresentation->streamInfo.inputLatency = 0.;+    streamRepresentation->streamInfo.outputLatency = 0.;+    streamRepresentation->streamInfo.sampleRate = 0.;+}+++void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation )+{+    streamRepresentation->magic = 0;+}+++PaError PaUtil_DummyRead( PaStream* stream,+                               void *buffer,+                               unsigned long frames )+{+    (void)stream; /* unused parameter */+    (void)buffer; /* unused parameter */+    (void)frames; /* unused parameter */++    return paCanNotReadFromACallbackStream;+}+++PaError PaUtil_DummyWrite( PaStream* stream,+                               const void *buffer,+                               unsigned long frames )+{+    (void)stream; /* unused parameter */+    (void)buffer; /* unused parameter */+    (void)frames; /* unused parameter */++    return paCanNotWriteToACallbackStream;+}+++signed long PaUtil_DummyGetReadAvailable( PaStream* stream )+{+    (void)stream; /* unused parameter */++    return paCanNotReadFromACallbackStream;+}+++signed long PaUtil_DummyGetWriteAvailable( PaStream* stream )+{+    (void)stream; /* unused parameter */++    return paCanNotWriteToACallbackStream;+}+++double PaUtil_DummyGetCpuLoad( PaStream* stream )+{+    (void)stream; /* unused parameter */++    return 0.0;+}
+ portaudio/src/common/pa_trace.c view
@@ -0,0 +1,238 @@+/*+ * $Id: pa_trace.c 1916 2014-01-17 03:45:15Z philburk $+ * Portable Audio I/O Library Trace Facility+ * Store trace information in real-time for later printing.+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2000 Phil Burk+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup common_src++ @brief Real-time safe event trace logging facility for debugging.+*/+++#include <stdio.h>+#include <stdlib.h>+#include <stdarg.h>+#include <string.h>+#include <assert.h>+#include "pa_trace.h"+#include "pa_util.h"+#include "pa_debugprint.h"++#if PA_TRACE_REALTIME_EVENTS++static char const *traceTextArray[PA_MAX_TRACE_RECORDS];+static int traceIntArray[PA_MAX_TRACE_RECORDS];+static int traceIndex = 0;+static int traceBlock = 0;++/*********************************************************************/+void PaUtil_ResetTraceMessages()+{+    traceIndex = 0;+}++/*********************************************************************/+void PaUtil_DumpTraceMessages()+{+    int i;+    int messageCount = (traceIndex < PA_MAX_TRACE_RECORDS) ? traceIndex : PA_MAX_TRACE_RECORDS;++    printf("DumpTraceMessages: traceIndex = %d\n", traceIndex );+    for( i=0; i<messageCount; i++ )+    {+        printf("%3d: %s = 0x%08X\n",+               i, traceTextArray[i], traceIntArray[i] );+    }+    PaUtil_ResetTraceMessages();+    fflush(stdout);+}++/*********************************************************************/+void PaUtil_AddTraceMessage( const char *msg, int data )+{+    if( (traceIndex == PA_MAX_TRACE_RECORDS) && (traceBlock == 0) )+    {+        traceBlock = 1;+        /*  PaUtil_DumpTraceMessages(); */+    }+    else if( traceIndex < PA_MAX_TRACE_RECORDS )+    {+        traceTextArray[traceIndex] = msg;+        traceIntArray[traceIndex] = data;+        traceIndex++;+    }+}++/************************************************************************/+/* High performance log alternative                                     */+/************************************************************************/++typedef unsigned long long  PaUint64;++typedef struct __PaHighPerformanceLog+{+    unsigned    magik;+    int         writePtr;+    int         readPtr;+    int         size;+    double      refTime;+    char*       data;+} PaHighPerformanceLog;++static const unsigned kMagik = 0xcafebabe;++#define USEC_PER_SEC    (1000000ULL)++int PaUtil_InitializeHighSpeedLog( LogHandle* phLog, unsigned maxSizeInBytes )+{+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)PaUtil_AllocateMemory(sizeof(PaHighPerformanceLog));+    if (pLog == 0)+    {+        return paInsufficientMemory;+    }+    assert(phLog != 0);+    *phLog = pLog;++    pLog->data = (char*)PaUtil_AllocateMemory(maxSizeInBytes);+    if (pLog->data == 0)+    {+        PaUtil_FreeMemory(pLog);+        return paInsufficientMemory;+    }+    pLog->magik = kMagik;+    pLog->size = maxSizeInBytes;+    pLog->refTime = PaUtil_GetTime();+    return paNoError;+}++void PaUtil_ResetHighSpeedLogTimeRef( LogHandle hLog )+{+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;+    assert(pLog->magik == kMagik);+    pLog->refTime = PaUtil_GetTime();+}++typedef struct __PaLogEntryHeader+{+    int    size;+    double timeStamp;+} PaLogEntryHeader;++#ifdef __APPLE__+#define _vsnprintf vsnprintf+#define min(a,b) ((a)<(b)?(a):(b))+#endif+++int PaUtil_AddHighSpeedLogMessage( LogHandle hLog, const char* fmt, ... )+{+    va_list l;+    int n = 0;+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;+    if (pLog != 0)+    {+        PaLogEntryHeader* pHeader;+        char* p;+        int maxN;+        assert(pLog->magik == kMagik);+        pHeader = (PaLogEntryHeader*)( pLog->data + pLog->writePtr );+        p = (char*)( pHeader + 1 );+        maxN = pLog->size - pLog->writePtr - 2 * sizeof(PaLogEntryHeader);++        pHeader->timeStamp = PaUtil_GetTime() - pLog->refTime;+        if (maxN > 0)+        {+            if (maxN > 32)+            {+                va_start(l, fmt);+                n = _vsnprintf(p, min(1024, maxN), fmt, l);+                va_end(l);+            }+            else {+                n = sprintf(p, "End of log...");+            }+            n = ((n + sizeof(unsigned)) & ~(sizeof(unsigned)-1)) + sizeof(PaLogEntryHeader);+            pHeader->size = n;+#if 0+            PaUtil_DebugPrint("%05u.%03u: %s\n", pHeader->timeStamp/1000, pHeader->timeStamp%1000, p);+#endif+            pLog->writePtr += n;+        }+    }+    return n;+}++void PaUtil_DumpHighSpeedLog( LogHandle hLog, const char* fileName )+{+    FILE* f = (fileName != NULL) ? fopen(fileName, "w") : stdout;+    unsigned localWritePtr;+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;+    assert(pLog->magik == kMagik);+    localWritePtr = pLog->writePtr;+    while (pLog->readPtr != localWritePtr)+    {+        const PaLogEntryHeader* pHeader = (const PaLogEntryHeader*)( pLog->data + pLog->readPtr );+        const char* p = (const char*)( pHeader + 1 );+        const PaUint64 ts = (const PaUint64)( pHeader->timeStamp * USEC_PER_SEC );+        assert(pHeader->size < (1024+sizeof(unsigned)+sizeof(PaLogEntryHeader)));+        fprintf(f, "%05u.%03u: %s\n", (unsigned)(ts/1000), (unsigned)(ts%1000), p);+        pLog->readPtr += pHeader->size;+    }+    if (f != stdout)+    {+        fclose(f);+    }+}++void PaUtil_DiscardHighSpeedLog( LogHandle hLog )+{+    PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;+    assert(pLog->magik == kMagik);+    PaUtil_FreeMemory(pLog->data);+    PaUtil_FreeMemory(pLog);+}++#else+/* This stub was added so that this file will generate a symbol.+ * Otherwise linker/archiver programs will complain.+ */+int PaUtil_TraceStubToSatisfyLinker(void)+{+	return 0;+}+#endif /* TRACE_REALTIME_EVENTS */
+ portaudio/src/hostapi/dsound/pa_win_ds.c view
@@ -0,0 +1,3240 @@+/*+ * $Id: pa_win_ds.c 1877 2012-11-10 02:55:20Z rbencina $+ * Portable Audio I/O Library DirectSound implementation+ *+ * Authors: Phil Burk, Robert Marsanyi & Ross Bencina+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2007 Ross Bencina, Phil Burk, Robert Marsanyi+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup hostapi_src+*/++/* Until May 2011 PA/DS has used a multimedia timer to perform the callback.+   We're replacing this with a new implementation using a thread and a different timer mechanim.+   Defining PA_WIN_DS_USE_WMME_TIMER uses the old (pre-May 2011) behavior.+*/+//#define PA_WIN_DS_USE_WMME_TIMER++#include <assert.h>+#include <stdio.h>+#include <string.h> /* strlen() */++#define _WIN32_WINNT 0x0400 /* required to get waitable timer APIs */+#include <initguid.h> /* make sure ds guids get defined */+#include <windows.h>+#include <objbase.h>+++/*+  Use the earliest version of DX required, no need to polute the namespace+*/+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+#define DIRECTSOUND_VERSION 0x0800+#else+#define DIRECTSOUND_VERSION 0x0300+#endif+#include <dsound.h>+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+#include <dsconf.h>+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */+#ifndef PA_WIN_DS_USE_WMME_TIMER+#ifndef UNDER_CE+#include <process.h>+#endif+#endif++#include "pa_util.h"+#include "pa_allocation.h"+#include "pa_hostapi.h"+#include "pa_stream.h"+#include "pa_cpuload.h"+#include "pa_process.h"+#include "pa_debugprint.h"++#include "pa_win_ds.h"+#include "pa_win_ds_dynlink.h"+#include "pa_win_waveformat.h"+#include "pa_win_wdmks_utils.h"+#include "pa_win_coinitialize.h"++#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */+#pragma comment( lib, "dsound.lib" )+#pragma comment( lib, "winmm.lib" )+#pragma comment( lib, "kernel32.lib" )+#endif++/* use CreateThread for CYGWIN, _beginthreadex for all others */+#ifndef PA_WIN_DS_USE_WMME_TIMER++#if !defined(__CYGWIN__) && !defined(UNDER_CE)+#define CREATE_THREAD (HANDLE)_beginthreadex+#undef CLOSE_THREAD_HANDLE /* as per documentation we don't call CloseHandle on a thread created with _beginthreadex */+#define PA_THREAD_FUNC static unsigned WINAPI+#define PA_THREAD_ID unsigned+#else+#define CREATE_THREAD CreateThread+#define CLOSE_THREAD_HANDLE CloseHandle+#define PA_THREAD_FUNC static DWORD WINAPI+#define PA_THREAD_ID DWORD+#endif++#if (defined(UNDER_CE))+#pragma comment(lib, "Coredll.lib")+#elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */+#pragma comment(lib, "winmm.lib")+#endif++PA_THREAD_FUNC ProcessingThreadProc( void *pArg );++#if !defined(UNDER_CE)+#define PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT /* use waitable timer where possible, otherwise we use a WaitForSingleObject timeout */+#endif++#endif /* !PA_WIN_DS_USE_WMME_TIMER */+++/*+ provided in newer platform sdks and x64+ */+#ifndef DWORD_PTR+    #if defined(_WIN64)+        #define DWORD_PTR unsigned __int64+    #else+        #define DWORD_PTR unsigned long+    #endif+#endif++#define PRINT(x) PA_DEBUG(x);+#define ERR_RPT(x) PRINT(x)+#define DBUG(x)   PRINT(x)+#define DBUGX(x)  PRINT(x)++#define PA_USE_HIGH_LATENCY   (0)+#if PA_USE_HIGH_LATENCY+#define PA_DS_WIN_9X_DEFAULT_LATENCY_     (.500)+#define PA_DS_WIN_NT_DEFAULT_LATENCY_     (.600)+#else+#define PA_DS_WIN_9X_DEFAULT_LATENCY_     (.140)+#define PA_DS_WIN_NT_DEFAULT_LATENCY_     (.280)+#endif++#define PA_DS_WIN_WDM_DEFAULT_LATENCY_    (.120)++/* we allow the polling period to range between 1 and 100ms.+   prior to August 2011 we limited the minimum polling period to 10ms.+*/+#define PA_DS_MINIMUM_POLLING_PERIOD_SECONDS    (0.001) /* 1ms */+#define PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS    (0.100) /* 100ms */+#define PA_DS_POLLING_JITTER_SECONDS            (0.001) /* 1ms */++#define SECONDS_PER_MSEC      (0.001)+#define MSECS_PER_SECOND       (1000)++/* prototypes for functions declared in this file */++#ifdef __cplusplus+extern "C"+{+#endif /* __cplusplus */++PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );++#ifdef __cplusplus+}+#endif /* __cplusplus */++static void Terminate( struct PaUtilHostApiRepresentation *hostApi );+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,+                           PaStream** s,+                           const PaStreamParameters *inputParameters,+                           const PaStreamParameters *outputParameters,+                           double sampleRate,+                           unsigned long framesPerBuffer,+                           PaStreamFlags streamFlags,+                           PaStreamCallback *streamCallback,+                           void *userData );+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,+                                  const PaStreamParameters *inputParameters,+                                  const PaStreamParameters *outputParameters,+                                  double sampleRate );+static PaError CloseStream( PaStream* stream );+static PaError StartStream( PaStream *stream );+static PaError StopStream( PaStream *stream );+static PaError AbortStream( PaStream *stream );+static PaError IsStreamStopped( PaStream *s );+static PaError IsStreamActive( PaStream *stream );+static PaTime GetStreamTime( PaStream *stream );+static double GetStreamCpuLoad( PaStream* stream );+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );+static signed long GetStreamReadAvailable( PaStream* stream );+static signed long GetStreamWriteAvailable( PaStream* stream );+++/* FIXME: should convert hr to a string */+#define PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ) \+    PaUtil_SetLastHostErrorInfo( paDirectSound, hr, "DirectSound error" )++/************************************************* DX Prototypes **********/+static BOOL CALLBACK CollectGUIDsProcA(LPGUID lpGUID,+                                     LPCSTR lpszDesc,+                                     LPCSTR lpszDrvName,+                                     LPVOID lpContext );++/************************************************************************************/+/********************** Structures **************************************************/+/************************************************************************************/+/* PaWinDsHostApiRepresentation - host api datastructure specific to this implementation */++typedef struct PaWinDsDeviceInfo+{+    PaDeviceInfo        inheritedDeviceInfo;+    GUID                guid;+    GUID                *lpGUID;+    double              sampleRates[3];+    char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/+    char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/+} PaWinDsDeviceInfo;++typedef struct+{+    PaUtilHostApiRepresentation inheritedHostApiRep;+    PaUtilStreamInterface    callbackStreamInterface;+    PaUtilStreamInterface    blockingStreamInterface;++    PaUtilAllocationGroup   *allocations;++    /* implementation specific data goes here */++    PaWinUtilComInitializationResult comInitializationResult;++} PaWinDsHostApiRepresentation;+++/* PaWinDsStream - a stream data structure specifically for this implementation */++typedef struct PaWinDsStream+{+    PaUtilStreamRepresentation streamRepresentation;+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;+    PaUtilBufferProcessor bufferProcessor;++/* DirectSound specific data. */+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+    LPDIRECTSOUNDFULLDUPLEX8 pDirectSoundFullDuplex8;+#endif++/* Output */+    LPDIRECTSOUND        pDirectSound;+    LPDIRECTSOUNDBUFFER  pDirectSoundPrimaryBuffer;+    LPDIRECTSOUNDBUFFER  pDirectSoundOutputBuffer;+    DWORD                outputBufferWriteOffsetBytes;     /* last write position */+    INT                  outputBufferSizeBytes;+    INT                  outputFrameSizeBytes;+    /* Try to detect play buffer underflows. */+    LARGE_INTEGER        perfCounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */+    LARGE_INTEGER        previousPlayTime;+    DWORD                previousPlayCursor;+    UINT                 outputUnderflowCount;+    BOOL                 outputIsRunning;+    INT                  finalZeroBytesWritten; /* used to determine when we've flushed the whole buffer */++/* Input */+    LPDIRECTSOUNDCAPTURE pDirectSoundCapture;+    LPDIRECTSOUNDCAPTUREBUFFER   pDirectSoundInputBuffer;+    INT                  inputFrameSizeBytes;+    UINT                 readOffset;      /* last read position */+    UINT                 inputBufferSizeBytes;++    +    int              hostBufferSizeFrames; /* input and output host ringbuffers have the same number of frames */+    double           framesWritten;+    double           secondsPerHostByte; /* Used to optimize latency calculation for outTime */+    double           pollingPeriodSeconds;++    PaStreamCallbackFlags callbackFlags;++    PaStreamFlags    streamFlags;+    int              callbackResult;+    HANDLE           processingCompleted;+    +/* FIXME - move all below to PaUtilStreamRepresentation */+    volatile int     isStarted;+    volatile int     isActive;+    volatile int     stopProcessing; /* stop thread once existing buffers have been returned */+    volatile int     abortProcessing; /* stop thread immediately */++    UINT             systemTimerResolutionPeriodMs; /* set to 0 if we were unable to set the timer period */ ++#ifdef PA_WIN_DS_USE_WMME_TIMER+    MMRESULT         timerID;+#else++#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT+    HANDLE           waitableTimer;+#endif+    HANDLE           processingThread;+    PA_THREAD_ID     processingThreadId;+    HANDLE           processingThreadCompleted;+#endif++} PaWinDsStream;+++/* Set minimal latency based on the current OS version.+ * NT has higher latency.+ */+static double PaWinDS_GetMinSystemLatencySeconds( void )+{+    double minLatencySeconds;+    /* Set minimal latency based on whether NT or other OS.+     * NT has higher latency.+     */+    OSVERSIONINFO osvi;+	osvi.dwOSVersionInfoSize = sizeof( osvi );+	GetVersionEx( &osvi );+    DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId ));+    DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion ));+    DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion ));+    /* Check for NT */+	if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )+	{+		minLatencySeconds = PA_DS_WIN_NT_DEFAULT_LATENCY_;+	}+	else if(osvi.dwMajorVersion >= 5)+	{+		minLatencySeconds = PA_DS_WIN_WDM_DEFAULT_LATENCY_;+	}+	else+	{+		minLatencySeconds = PA_DS_WIN_9X_DEFAULT_LATENCY_;+	}+    return minLatencySeconds;+}+++/*************************************************************************+** Return minimum workable latency required for this host. This is returned+** As the default stream latency in PaDeviceInfo.+** Latency can be optionally set by user by setting an environment variable. +** For example, to set latency to 200 msec, put:+**+**    set PA_MIN_LATENCY_MSEC=200+**+** in the AUTOEXEC.BAT file and reboot.+** If the environment variable is not set, then the latency will be determined+** based on the OS. Windows NT has higher latency than Win95.+*/+#define PA_LATENCY_ENV_NAME  ("PA_MIN_LATENCY_MSEC")+#define PA_ENV_BUF_SIZE  (32)++static double PaWinDs_GetMinLatencySeconds( double sampleRate )+{+    char      envbuf[PA_ENV_BUF_SIZE];+    DWORD     hresult;+    double    minLatencySeconds = 0;++    /* Let user determine minimal latency by setting environment variable. */+    hresult = GetEnvironmentVariableA( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE );+    if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) )+    {+        minLatencySeconds = atoi( envbuf ) * SECONDS_PER_MSEC;+    }+    else+    {+        minLatencySeconds = PaWinDS_GetMinSystemLatencySeconds();+#if PA_USE_HIGH_LATENCY+        PRINT(("PA - Minimum Latency set to %f msec!\n", minLatencySeconds * MSECS_PER_SECOND ));+#endif+    }++    return minLatencySeconds;+}+++/************************************************************************************+** Duplicate the input string using the allocations allocator.+** A NULL string is converted to a zero length string.+** If memory cannot be allocated, NULL is returned.+**/+static char *DuplicateDeviceNameString( PaUtilAllocationGroup *allocations, const char* src )+{+    char *result = 0;+    +    if( src != NULL )+    {+        size_t len = strlen(src);+        result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) );+        if( result )+            memcpy( (void *) result, src, len+1 );+    }+    else+    {+        result = (char*)PaUtil_GroupAllocateMemory( allocations, 1 );+        if( result )+            result[0] = '\0';+    }++    return result;+}++/************************************************************************************+** DSDeviceNameAndGUID, DSDeviceNameAndGUIDVector used for collecting preliminary+** information during device enumeration.+*/+typedef struct DSDeviceNameAndGUID{+    char *name; // allocated from parent's allocations, never deleted by this structure+    GUID guid;+    LPGUID lpGUID;+    void *pnpInterface;  // wchar_t* interface path, allocated using the DS host api's allocation group+} DSDeviceNameAndGUID;++typedef struct DSDeviceNameAndGUIDVector{+    PaUtilAllocationGroup *allocations;+    PaError enumerationError;++    int count;+    int free;+    DSDeviceNameAndGUID *items; // Allocated using LocalAlloc()+} DSDeviceNameAndGUIDVector;++typedef struct DSDeviceNamesAndGUIDs{+    PaWinDsHostApiRepresentation *winDsHostApi;+    DSDeviceNameAndGUIDVector inputNamesAndGUIDs;+    DSDeviceNameAndGUIDVector outputNamesAndGUIDs;+} DSDeviceNamesAndGUIDs;++static PaError InitializeDSDeviceNameAndGUIDVector(+        DSDeviceNameAndGUIDVector *guidVector, PaUtilAllocationGroup *allocations )+{+    PaError result = paNoError;++    guidVector->allocations = allocations;+    guidVector->enumerationError = paNoError;++    guidVector->count = 0;+    guidVector->free = 8;+    guidVector->items = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * guidVector->free );+    if( guidVector->items == NULL )+        result = paInsufficientMemory;+    +    return result;+}++static PaError ExpandDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )+{+    PaError result = paNoError;+    DSDeviceNameAndGUID *newItems;+    int i;+    +    /* double size of vector */+    int size = guidVector->count + guidVector->free;+    guidVector->free += size;++    newItems = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * size * 2 );+    if( newItems == NULL )+    {+        result = paInsufficientMemory;+    }+    else+    {+        for( i=0; i < guidVector->count; ++i )+        {+            newItems[i].name = guidVector->items[i].name;+            if( guidVector->items[i].lpGUID == NULL )+            {+                newItems[i].lpGUID = NULL;+            }+            else+            {+                newItems[i].lpGUID = &newItems[i].guid;+                memcpy( &newItems[i].guid, guidVector->items[i].lpGUID, sizeof(GUID) );+            }+            newItems[i].pnpInterface = guidVector->items[i].pnpInterface;+        }++        LocalFree( guidVector->items );+        guidVector->items = newItems;+    }                                ++    return result;+}++/*+    it's safe to call DSDeviceNameAndGUIDVector multiple times+*/+static PaError TerminateDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )+{+    PaError result = paNoError;++    if( guidVector->items != NULL )+    {+        if( LocalFree( guidVector->items ) != NULL )+            result = paInsufficientMemory;              /** @todo this isn't the correct error to return from a deallocation failure */++        guidVector->items = NULL;+    }++    return result;+}++/************************************************************************************+** Collect preliminary device information during DirectSound enumeration +*/+static BOOL CALLBACK CollectGUIDsProcA(LPGUID lpGUID,+                                     LPCSTR lpszDesc,+                                     LPCSTR lpszDrvName,+                                     LPVOID lpContext )+{+    DSDeviceNameAndGUIDVector *namesAndGUIDs = (DSDeviceNameAndGUIDVector*)lpContext;+    PaError error;++    (void) lpszDrvName; /* unused variable */++    if( namesAndGUIDs->free == 0 )+    {+        error = ExpandDSDeviceNameAndGUIDVector( namesAndGUIDs );+        if( error != paNoError )+        {+            namesAndGUIDs->enumerationError = error;+            return FALSE;+        }+    }+    +    /* Set GUID pointer, copy GUID to storage in DSDeviceNameAndGUIDVector. */+    if( lpGUID == NULL )+    {+        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = NULL;+    }+    else+    {+        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID =+                &namesAndGUIDs->items[namesAndGUIDs->count].guid;+      +        memcpy( &namesAndGUIDs->items[namesAndGUIDs->count].guid, lpGUID, sizeof(GUID) );+    }++    namesAndGUIDs->items[namesAndGUIDs->count].name =+            DuplicateDeviceNameString( namesAndGUIDs->allocations, lpszDesc );+    if( namesAndGUIDs->items[namesAndGUIDs->count].name == NULL )+    {+        namesAndGUIDs->enumerationError = paInsufficientMemory;+        return FALSE;+    }++    namesAndGUIDs->items[namesAndGUIDs->count].pnpInterface = 0;++    ++namesAndGUIDs->count;+    --namesAndGUIDs->free;+    +    return TRUE;+}+++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO++static void *DuplicateWCharString( PaUtilAllocationGroup *allocations, wchar_t *source )+{+    size_t len;+    wchar_t *result;++    len = wcslen( source );+    result = (wchar_t*)PaUtil_GroupAllocateMemory( allocations, (long) ((len+1) * sizeof(wchar_t)) );+    wcscpy( result, source );+    return result;+}++static BOOL CALLBACK KsPropertySetEnumerateCallback( PDSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA data, LPVOID context )+{+    int i;+    DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs = (DSDeviceNamesAndGUIDs*)context;++    /*+        Apparently data->Interface can be NULL in some cases. +        Possibly virtual devices without hardware.+        So we check for NULLs now. See mailing list message November 10, 2012:+        "[Portaudio] portaudio initialization crash in KsPropertySetEnumerateCallback(pa_win_ds.c)"+    */+    if( data->Interface )+    {+        if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_RENDER )+        {+            for( i=0; i < deviceNamesAndGUIDs->outputNamesAndGUIDs.count; ++i )+            {+                if( deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID+                    && memcmp( &data->DeviceId, deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )+                {+                    deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].pnpInterface = +                        (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );+                    break;+                }+            }+        }+        else if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE )+        {+            for( i=0; i < deviceNamesAndGUIDs->inputNamesAndGUIDs.count; ++i )+            {+                if( deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID+                    && memcmp( &data->DeviceId, deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )+                {+                    deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].pnpInterface = +                        (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );+                    break;+                }+            }+        }+    }++    return TRUE;+}+++static GUID pawin_CLSID_DirectSoundPrivate = +{ 0x11ab3ec0, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };++static GUID pawin_DSPROPSETID_DirectSoundDevice = +{ 0x84624f82, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };++static GUID pawin_IID_IKsPropertySet = +{ 0x31efac30, 0x515c, 0x11d0, 0xa9, 0xaa, 0x00, 0xaa, 0x00, 0x61, 0xbe, 0x93 };+++/*+    FindDevicePnpInterfaces fills in the pnpInterface fields in deviceNamesAndGUIDs+    with UNICODE file paths to the devices. The DS documentation mentions+    at least two techniques by which these Interface paths can be found using IKsPropertySet on+    the DirectSound class object. One is using the DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION +    property, and the other is using DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE.+    I tried both methods and only the second worked. I found two postings on the+    net from people who had the same problem with the first method, so I think the method used here is +    more common/likely to work. The probem is that IKsPropertySet_Get returns S_OK+    but the fields of the device description are not filled in.++    The mechanism we use works by registering an enumeration callback which is called for +    every DSound device. Our callback searches for a device in our deviceNamesAndGUIDs list+    with the matching GUID and copies the pointer to the Interface path.+    Note that we could have used this enumeration callback to perform the original +    device enumeration, however we choose not to so we can disable this step easily.++    Apparently the IKsPropertySet mechanism was added in DirectSound 9c 2004+    http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.mmedia/2004-12/0099.html++        -- rossb+*/+static void FindDevicePnpInterfaces( DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs )+{+    IClassFactory *pClassFactory;+   +    if( paWinDsDSoundEntryPoints.DllGetClassObject(&pawin_CLSID_DirectSoundPrivate, &IID_IClassFactory, (PVOID *) &pClassFactory) == S_OK ){+        IKsPropertySet *pPropertySet;+        if( pClassFactory->lpVtbl->CreateInstance( pClassFactory, NULL, &pawin_IID_IKsPropertySet, (PVOID *) &pPropertySet) == S_OK ){+            +            DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA data;+            ULONG bytesReturned;++            data.Callback = KsPropertySetEnumerateCallback;+            data.Context = deviceNamesAndGUIDs;++            IKsPropertySet_Get( pPropertySet,+                &pawin_DSPROPSETID_DirectSoundDevice,+                DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W,+                NULL,+                0,+                &data,+                sizeof(data),+                &bytesReturned+            );+            +            IKsPropertySet_Release( pPropertySet );+        }+        pClassFactory->lpVtbl->Release( pClassFactory );+    }++    /*+        The following code fragment, which I chose not to use, queries for the +        device interface for a device with a specific GUID:++        ULONG BytesReturned;+        DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA Property;++        memset (&Property, 0, sizeof(Property));+        Property.DataFlow = DIRECTSOUNDDEVICE_DATAFLOW_RENDER;+        Property.DeviceId = *lpGUID;  ++        hr = IKsPropertySet_Get( pPropertySet,+            &pawin_DSPROPSETID_DirectSoundDevice,+            DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W,+            NULL,+            0,+            &Property,+            sizeof(Property),+            &BytesReturned+        );++        if( hr == S_OK )+        {+            //pnpInterface = Property.Interface;+        }+    */+}+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */+++/* +    GUIDs for emulated devices which we blacklist below.+    are there more than two of them??+*/++GUID IID_IRolandVSCEmulated1 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x01};+GUID IID_IRolandVSCEmulated2 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x02};+++#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_  (13) /* must match array length below */+static double defaultSampleRateSearchOrder_[] =+    { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,+        16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };++/************************************************************************************+** Extract capabilities from an output device, and add it to the device info list+** if successful. This function assumes that there is enough room in the+** device info list to accomodate all entries.+**+** The device will not be added to the device list if any errors are encountered.+*/+static PaError AddOutputDeviceInfoFromDirectSound(+        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )+{+    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;+    PaWinDsDeviceInfo            *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];+    PaDeviceInfo                 *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;+    HRESULT                       hr;+    LPDIRECTSOUND                 lpDirectSound;+    DSCAPS                        caps;+    int                           deviceOK = TRUE;+    PaError                       result = paNoError;+    int                           i;++    /* Copy GUID to the device info structure. Set pointer. */+    if( lpGUID == NULL )+    {+        winDsDeviceInfo->lpGUID = NULL;+    }+    else+    {+        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );+        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;+    }+    +    if( lpGUID )+    {+        if (IsEqualGUID (&IID_IRolandVSCEmulated1,lpGUID) ||+            IsEqualGUID (&IID_IRolandVSCEmulated2,lpGUID) )+        {+            PA_DEBUG(("BLACKLISTED: %s \n",name));+            return paNoError;+        }+    }++    /* Create a DirectSound object for the specified GUID+        Note that using CoCreateInstance doesn't work on windows CE.+    */+    hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &lpDirectSound, NULL );++    /** try using CoCreateInstance because DirectSoundCreate was hanging under+        some circumstances - note this was probably related to the+        #define BOOL short bug which has now been fixed+        @todo delete this comment and the following code once we've ensured+        there is no bug.+    */+    /*+    hr = CoCreateInstance( &CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER,+            &IID_IDirectSound, (void**)&lpDirectSound );++    if( hr == S_OK )+    {+        hr = IDirectSound_Initialize( lpDirectSound, lpGUID );+    }+    */+    +    if( hr != DS_OK )+    {+        if (hr == DSERR_ALLOCATED)+            PA_DEBUG(("AddOutputDeviceInfoFromDirectSound %s DSERR_ALLOCATED\n",name));+        DBUG(("Cannot create DirectSound for %s. Result = 0x%x\n", name, hr ));+        if (lpGUID)+            DBUG(("%s's GUID: {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, 0x%x} \n",+                 name,+                 lpGUID->Data1,+                 lpGUID->Data2,+                 lpGUID->Data3,+                 lpGUID->Data4[0],+                 lpGUID->Data4[1],+                 lpGUID->Data4[2],+                 lpGUID->Data4[3],+                 lpGUID->Data4[4],+                 lpGUID->Data4[5],+                 lpGUID->Data4[6],+                 lpGUID->Data4[7]));++        deviceOK = FALSE;+    }+    else+    {+        /* Query device characteristics. */+        memset( &caps, 0, sizeof(caps) ); +        caps.dwSize = sizeof(caps);+        hr = IDirectSound_GetCaps( lpDirectSound, &caps );+        if( hr != DS_OK )+        {+            DBUG(("Cannot GetCaps() for DirectSound device %s. Result = 0x%x\n", name, hr ));+            deviceOK = FALSE;+        }+        else+        {++#if PA_USE_WMME+            if( caps.dwFlags & DSCAPS_EMULDRIVER )+            {+                /* If WMME supported, then reject Emulated drivers because they are lousy. */+                deviceOK = FALSE;+            }+#endif++            if( deviceOK )+            {+                deviceInfo->maxInputChannels = 0;+                winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;++                /* DS output capabilities only indicate supported number of channels+                   using two flags which indicate mono and/or stereo.+                   We assume that stereo devices may support more than 2 channels+                   (as is the case with 5.1 devices for example) and so+                   set deviceOutputChannelCountIsKnown to 0 (unknown).+                   In this case OpenStream will try to open the device+                   when the user requests more than 2 channels, rather than+                   returning an error. +                */+                if( caps.dwFlags & DSCAPS_PRIMARYSTEREO )+                {+                    deviceInfo->maxOutputChannels = 2;+                    winDsDeviceInfo->deviceOutputChannelCountIsKnown = 0;+                }+                else+                {+                    deviceInfo->maxOutputChannels = 1;+                    winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;+                }++                /* Guess channels count from speaker configuration. We do it only when +                   pnpInterface is NULL or when PAWIN_USE_WDMKS_DEVICE_INFO is undefined.+                */+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+                if( !pnpInterface )+#endif+                {+                    DWORD spkrcfg;+                    if( SUCCEEDED(IDirectSound_GetSpeakerConfig( lpDirectSound, &spkrcfg )) )+                    {+                        int count = 0;+                        switch (DSSPEAKER_CONFIG(spkrcfg))+                        {+                            case DSSPEAKER_HEADPHONE:        count = 2; break;+                            case DSSPEAKER_MONO:             count = 1; break;+                            case DSSPEAKER_QUAD:             count = 4; break;+                            case DSSPEAKER_STEREO:           count = 2; break;+                            case DSSPEAKER_SURROUND:         count = 4; break;+                            case DSSPEAKER_5POINT1:          count = 6; break;+                            case DSSPEAKER_7POINT1:          count = 8; break;+#ifndef DSSPEAKER_7POINT1_SURROUND+#define DSSPEAKER_7POINT1_SURROUND 0x00000008+#endif                            +                            case DSSPEAKER_7POINT1_SURROUND: count = 8; break;+#ifndef DSSPEAKER_5POINT1_SURROUND+#define DSSPEAKER_5POINT1_SURROUND 0x00000009+#endif+                            case DSSPEAKER_5POINT1_SURROUND: count = 6; break;+                        }+                        if( count )+                        {+                            deviceInfo->maxOutputChannels = count;+                            winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;+                        }+                    }+                }++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+                if( pnpInterface )+                {+                    int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 0  );+                    if( count > 0 )+                    {+                        deviceInfo->maxOutputChannels = count;+                        winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;+                    }+                }+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */++                /* initialize defaultSampleRate */+                +                if( caps.dwFlags & DSCAPS_CONTINUOUSRATE )+                {+                    /* initialize to caps.dwMaxSecondarySampleRate incase none of the standard rates match */+                    deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;++                    for( i = 0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )+                    {+                        if( defaultSampleRateSearchOrder_[i] >= caps.dwMinSecondarySampleRate+                                && defaultSampleRateSearchOrder_[i] <= caps.dwMaxSecondarySampleRate )+                        {+                            deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[i];+                            break;+                        }+                    }+                }+                else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate )+                {+                    if( caps.dwMinSecondarySampleRate == 0 )+                    {+                        /*+                        ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !!+                        ** But it supports continuous sampling.+                        ** So fake range of rates, and hope it really supports it.+                        */+                        deviceInfo->defaultSampleRate = 48000.0f;  /* assume 48000 as the default */++                        DBUG(("PA - Reported rates both zero. Setting to fake values for device #%s\n", name ));+                    }+                    else+                    {+	                    deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;+                    }+                }+                else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) )+                {+                    /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000.+                    ** But we know that they really support a range of rates!+                    ** So when we see a ridiculous set of rates, assume it is a range.+                    */+                  deviceInfo->defaultSampleRate = 48000.0f;  /* assume 48000 as the default */+                  DBUG(("PA - Sample rate range used instead of two odd values for device #%s\n", name ));+                }+                else deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;++                //printf( "min %d max %d\n", caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate );+                // dwFlags | DSCAPS_CONTINUOUSRATE ++                deviceInfo->defaultLowInputLatency = 0.;+                deviceInfo->defaultHighInputLatency = 0.;++                deviceInfo->defaultLowOutputLatency = PaWinDs_GetMinLatencySeconds( deviceInfo->defaultSampleRate );+                deviceInfo->defaultHighOutputLatency = deviceInfo->defaultLowOutputLatency * 2;+            }+        }++        IDirectSound_Release( lpDirectSound );+    }++    if( deviceOK )+    {+        deviceInfo->name = name;++        if( lpGUID == NULL )+            hostApi->info.defaultOutputDevice = hostApi->info.deviceCount;+            +        hostApi->info.deviceCount++;+    }++    return result;+}+++/************************************************************************************+** Extract capabilities from an input device, and add it to the device info list+** if successful. This function assumes that there is enough room in the+** device info list to accomodate all entries.+**+** The device will not be added to the device list if any errors are encountered.+*/+static PaError AddInputDeviceInfoFromDirectSoundCapture(+        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )+{+    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;+    PaWinDsDeviceInfo            *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];+    PaDeviceInfo                 *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;+    HRESULT                       hr;+    LPDIRECTSOUNDCAPTURE          lpDirectSoundCapture;+    DSCCAPS                       caps;+    int                           deviceOK = TRUE;+    PaError                       result = paNoError;+    +    /* Copy GUID to the device info structure. Set pointer. */+    if( lpGUID == NULL )+    {+        winDsDeviceInfo->lpGUID = NULL;+    }+    else+    {+        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;+        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );+    }++    hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL );++    /** try using CoCreateInstance because DirectSoundCreate was hanging under+        some circumstances - note this was probably related to the+        #define BOOL short bug which has now been fixed+        @todo delete this comment and the following code once we've ensured+        there is no bug.+    */+    /*+    hr = CoCreateInstance( &CLSID_DirectSoundCapture, NULL, CLSCTX_INPROC_SERVER,+            &IID_IDirectSoundCapture, (void**)&lpDirectSoundCapture );+    */+    if( hr != DS_OK )+    {+        DBUG(("Cannot create Capture for %s. Result = 0x%x\n", name, hr ));+        deviceOK = FALSE;+    }+    else+    {+        /* Query device characteristics. */+        memset( &caps, 0, sizeof(caps) );+        caps.dwSize = sizeof(caps);+        hr = IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps );+        if( hr != DS_OK )+        {+            DBUG(("Cannot GetCaps() for Capture device %s. Result = 0x%x\n", name, hr ));+            deviceOK = FALSE;+        }+        else+        {+#if PA_USE_WMME+            if( caps.dwFlags & DSCAPS_EMULDRIVER )+            {+                /* If WMME supported, then reject Emulated drivers because they are lousy. */+                deviceOK = FALSE;+            }+#endif++            if( deviceOK )+            {+                deviceInfo->maxInputChannels = caps.dwChannels;+                winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;++                deviceInfo->maxOutputChannels = 0;+                winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+                if( pnpInterface )+                {+                    int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 1  );+                    if( count > 0 )+                    {+                        deviceInfo->maxInputChannels = count;+                        winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;+                    }+                }+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */++/*  constants from a WINE patch by Francois Gouget, see:+    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html++    ---+    Date: Fri, 14 May 2004 10:38:12 +0200 (CEST)+    From: Francois Gouget <fgouget@ ... .fr>+    To: Ross Bencina <rbencina@ ... .au>+    Subject: Re: Permission to use wine 48/96 wave patch in BSD licensed library++    [snip]++    I give you permission to use the patch below under the BSD license.+    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html++    [snip]+*/+#ifndef WAVE_FORMAT_48M08+#define WAVE_FORMAT_48M08      0x00001000    /* 48     kHz, Mono,   8-bit  */+#define WAVE_FORMAT_48S08      0x00002000    /* 48     kHz, Stereo, 8-bit  */+#define WAVE_FORMAT_48M16      0x00004000    /* 48     kHz, Mono,   16-bit */+#define WAVE_FORMAT_48S16      0x00008000    /* 48     kHz, Stereo, 16-bit */+#define WAVE_FORMAT_96M08      0x00010000    /* 96     kHz, Mono,   8-bit  */+#define WAVE_FORMAT_96S08      0x00020000    /* 96     kHz, Stereo, 8-bit  */+#define WAVE_FORMAT_96M16      0x00040000    /* 96     kHz, Mono,   16-bit */+#define WAVE_FORMAT_96S16      0x00080000    /* 96     kHz, Stereo, 16-bit */+#endif++                /* defaultSampleRate */+                if( caps.dwChannels == 2 )+                {+                    if( caps.dwFormats & WAVE_FORMAT_4S16 )+                        deviceInfo->defaultSampleRate = 44100.0;+                    else if( caps.dwFormats & WAVE_FORMAT_48S16 )+                        deviceInfo->defaultSampleRate = 48000.0;+                    else if( caps.dwFormats & WAVE_FORMAT_2S16 )+                        deviceInfo->defaultSampleRate = 22050.0;+                    else if( caps.dwFormats & WAVE_FORMAT_1S16 )+                        deviceInfo->defaultSampleRate = 11025.0;+                    else if( caps.dwFormats & WAVE_FORMAT_96S16 )+                        deviceInfo->defaultSampleRate = 96000.0;+                    else+                        deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */+                }+                else if( caps.dwChannels == 1 )+                {+                    if( caps.dwFormats & WAVE_FORMAT_4M16 )+                        deviceInfo->defaultSampleRate = 44100.0;+                    else if( caps.dwFormats & WAVE_FORMAT_48M16 )+                        deviceInfo->defaultSampleRate = 48000.0;+                    else if( caps.dwFormats & WAVE_FORMAT_2M16 )+                        deviceInfo->defaultSampleRate = 22050.0;+                    else if( caps.dwFormats & WAVE_FORMAT_1M16 )+                        deviceInfo->defaultSampleRate = 11025.0;+                    else if( caps.dwFormats & WAVE_FORMAT_96M16 )+                        deviceInfo->defaultSampleRate = 96000.0;+                    else+                        deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */+                }+                else deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */++                deviceInfo->defaultLowInputLatency = PaWinDs_GetMinLatencySeconds( deviceInfo->defaultSampleRate );+                deviceInfo->defaultHighInputLatency = deviceInfo->defaultLowInputLatency * 2;+        +                deviceInfo->defaultLowOutputLatency = 0.;+                deviceInfo->defaultHighOutputLatency = 0.;+            }+        }+        +        IDirectSoundCapture_Release( lpDirectSoundCapture );+    }++    if( deviceOK )+    {+        deviceInfo->name = name;++        if( lpGUID == NULL )+            hostApi->info.defaultInputDevice = hostApi->info.deviceCount;++        hostApi->info.deviceCount++;+    }++    return result;+}+++/***********************************************************************************/+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )+{+    PaError result = paNoError;+    int i, deviceCount;+    PaWinDsHostApiRepresentation *winDsHostApi;+    DSDeviceNamesAndGUIDs deviceNamesAndGUIDs;+    PaWinDsDeviceInfo *deviceInfoArray;++    PaWinDs_InitializeDSoundEntryPoints();++    /* initialise guid vectors so they can be safely deleted on error */+    deviceNamesAndGUIDs.winDsHostApi = NULL;+    deviceNamesAndGUIDs.inputNamesAndGUIDs.items = NULL;+    deviceNamesAndGUIDs.outputNamesAndGUIDs.items = NULL;++    winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) );+    if( !winDsHostApi )+    {+        result = paInsufficientMemory;+        goto error;+    }++    memset( winDsHostApi, 0, sizeof(PaWinDsHostApiRepresentation) ); /* ensure all fields are zeroed. especially winDsHostApi->allocations */++    result = PaWinUtil_CoInitialize( paDirectSound, &winDsHostApi->comInitializationResult );+    if( result != paNoError )+    {+        goto error;+    }++    winDsHostApi->allocations = PaUtil_CreateAllocationGroup();+    if( !winDsHostApi->allocations )+    {+        result = paInsufficientMemory;+        goto error;+    }++    *hostApi = &winDsHostApi->inheritedHostApiRep;+    (*hostApi)->info.structVersion = 1;+    (*hostApi)->info.type = paDirectSound;+    (*hostApi)->info.name = "Windows DirectSound";+    +    (*hostApi)->info.deviceCount = 0;+    (*hostApi)->info.defaultInputDevice = paNoDevice;+    (*hostApi)->info.defaultOutputDevice = paNoDevice;++    +/* DSound - enumerate devices to count them and to gather their GUIDs */++    result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs, winDsHostApi->allocations );+    if( result != paNoError )+        goto error;++    result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs, winDsHostApi->allocations );+    if( result != paNoError )+        goto error;++    paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA( (LPDSENUMCALLBACKA)CollectGUIDsProcA, (void *)&deviceNamesAndGUIDs.inputNamesAndGUIDs );++    paWinDsDSoundEntryPoints.DirectSoundEnumerateA( (LPDSENUMCALLBACKA)CollectGUIDsProcA, (void *)&deviceNamesAndGUIDs.outputNamesAndGUIDs );++    if( deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError != paNoError )+    {+        result = deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError;+        goto error;+    }++    if( deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError != paNoError )+    {+        result = deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError;+        goto error;+    }++    deviceCount = deviceNamesAndGUIDs.inputNamesAndGUIDs.count + deviceNamesAndGUIDs.outputNamesAndGUIDs.count;++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+    if( deviceCount > 0 )+    {+        deviceNamesAndGUIDs.winDsHostApi = winDsHostApi;+        FindDevicePnpInterfaces( &deviceNamesAndGUIDs );+    }+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */++    if( deviceCount > 0 )+    {+        /* allocate array for pointers to PaDeviceInfo structs */+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(+                winDsHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );+        if( !(*hostApi)->deviceInfos )+        {+            result = paInsufficientMemory;+            goto error;+        }++        /* allocate all PaDeviceInfo structs in a contiguous block */+        deviceInfoArray = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory(+                winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount );+        if( !deviceInfoArray )+        {+            result = paInsufficientMemory;+            goto error;+        }++        for( i=0; i < deviceCount; ++i )+        {+            PaDeviceInfo *deviceInfo = &deviceInfoArray[i].inheritedDeviceInfo;+            deviceInfo->structVersion = 2;+            deviceInfo->hostApi = hostApiIndex;+            deviceInfo->name = 0;+            (*hostApi)->deviceInfos[i] = deviceInfo;+        }++        for( i=0; i < deviceNamesAndGUIDs.inputNamesAndGUIDs.count; ++i )+        {+            result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi,+                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].name,+                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].lpGUID,+                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].pnpInterface );+            if( result != paNoError )+                goto error;+        }++        for( i=0; i < deviceNamesAndGUIDs.outputNamesAndGUIDs.count; ++i )+        {+            result = AddOutputDeviceInfoFromDirectSound( winDsHostApi,+                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].name,+                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].lpGUID,+                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].pnpInterface );+            if( result != paNoError )+                goto error;+        }+    }    ++    result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );+    if( result != paNoError )+        goto error;++    result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );+    if( result != paNoError )+        goto error;++    +    (*hostApi)->Terminate = Terminate;+    (*hostApi)->OpenStream = OpenStream;+    (*hostApi)->IsFormatSupported = IsFormatSupported;++    PaUtil_InitializeStreamInterface( &winDsHostApi->callbackStreamInterface, CloseStream, StartStream,+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,+                                      GetStreamTime, GetStreamCpuLoad,+                                      PaUtil_DummyRead, PaUtil_DummyWrite,+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );++    PaUtil_InitializeStreamInterface( &winDsHostApi->blockingStreamInterface, CloseStream, StartStream,+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );++    return result;++error:+    TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );+    TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );++    Terminate( (struct PaUtilHostApiRepresentation *)winDsHostApi );++    return result;+}+++/***********************************************************************************/+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )+{+    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;++    if( winDsHostApi ){+        if( winDsHostApi->allocations )+        {+            PaUtil_FreeAllAllocations( winDsHostApi->allocations );+            PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );+        }++        PaWinUtil_CoUninitialize( paDirectSound, &winDsHostApi->comInitializationResult );++        PaUtil_FreeMemory( winDsHostApi );+    }++    PaWinDs_TerminateDSoundEntryPoints();+}++static PaError ValidateWinDirectSoundSpecificStreamInfo(+        const PaStreamParameters *streamParameters,+        const PaWinDirectSoundStreamInfo *streamInfo )+{+	if( streamInfo )+	{+	    if( streamInfo->size != sizeof( PaWinDirectSoundStreamInfo )+	            || streamInfo->version != 2 )+	    {+	        return paIncompatibleHostApiSpecificStreamInfo;+	    }++        if( streamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )+        {+            if( streamInfo->framesPerBuffer <= 0 )+                return paIncompatibleHostApiSpecificStreamInfo;++        }+	}++	return paNoError;+}++/***********************************************************************************/+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,+                                  const PaStreamParameters *inputParameters,+                                  const PaStreamParameters *outputParameters,+                                  double sampleRate )+{+    PaError result;+    PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;+    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;+    int inputChannelCount, outputChannelCount;+    PaSampleFormat inputSampleFormat, outputSampleFormat;+    PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;++    if( inputParameters )+    {+        inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];+        inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;++        inputChannelCount = inputParameters->channelCount;+        inputSampleFormat = inputParameters->sampleFormat;++        /* unless alternate device specification is supported, reject the use of+            paUseHostApiSpecificDeviceSpecification */++        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )+            return paInvalidDevice;++        /* check that input device can support inputChannelCount */+        if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown+                && inputChannelCount > inputDeviceInfo->maxInputChannels )+            return paInvalidChannelCount;++        /* validate inputStreamInfo */+        inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;+		result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );+		if( result != paNoError ) return result;+    }+    else+    {+        inputChannelCount = 0;+    }++    if( outputParameters )+    {+        outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];+        outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;++        outputChannelCount = outputParameters->channelCount;+        outputSampleFormat = outputParameters->sampleFormat;+        +        /* unless alternate device specification is supported, reject the use of+            paUseHostApiSpecificDeviceSpecification */++        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )+            return paInvalidDevice;++        /* check that output device can support inputChannelCount */+        if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown+                && outputChannelCount > outputDeviceInfo->maxOutputChannels )+            return paInvalidChannelCount;++        /* validate outputStreamInfo */+        outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;+		result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );+		if( result != paNoError ) return result;+    }+    else+    {+        outputChannelCount = 0;+    }+    +    /*+        IMPLEMENT ME:++            - if a full duplex stream is requested, check that the combination+                of input and output parameters is supported if necessary++            - check that the device supports sampleRate++        Because the buffer adapter handles conversion between all standard+        sample formats, the following checks are only required if paCustomFormat+        is implemented, or under some other unusual conditions.++            - check that input device can support inputSampleFormat, or that+                we have the capability to convert from outputSampleFormat to+                a native format++            - check that output device can support outputSampleFormat, or that+                we have the capability to convert from outputSampleFormat to+                a native format+    */++    return paFormatIsSupported;+}+++#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+static HRESULT InitFullDuplexInputOutputBuffers( PaWinDsStream *stream,+                                       PaWinDsDeviceInfo *inputDevice,+                                       PaSampleFormat hostInputSampleFormat,+                                       WORD inputChannelCount, +                                       int bytesPerInputBuffer,+                                       PaWinWaveFormatChannelMask inputChannelMask,+                                       PaWinDsDeviceInfo *outputDevice,+                                       PaSampleFormat hostOutputSampleFormat,+                                       WORD outputChannelCount, +                                       int bytesPerOutputBuffer,+                                       PaWinWaveFormatChannelMask outputChannelMask,+                                       unsigned long nFrameRate+                                        )+{+    HRESULT hr;+    DSCBUFFERDESC  captureDesc;+    PaWinWaveFormat captureWaveFormat;+    DSBUFFERDESC   secondaryRenderDesc;+    PaWinWaveFormat renderWaveFormat;+    LPDIRECTSOUNDBUFFER8 pRenderBuffer8;+    LPDIRECTSOUNDCAPTUREBUFFER8 pCaptureBuffer8;++    // capture buffer description++    // only try wave format extensible. assume it's available on all ds 8 systems+    PaWin_InitializeWaveFormatExtensible( &captureWaveFormat, inputChannelCount, +                hostInputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostInputSampleFormat ),+                nFrameRate, inputChannelMask );++    ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));+    captureDesc.dwSize = sizeof(DSCBUFFERDESC);+    captureDesc.dwFlags = 0;+    captureDesc.dwBufferBytes = bytesPerInputBuffer;+    captureDesc.lpwfxFormat = (WAVEFORMATEX*)&captureWaveFormat;++    // render buffer description++    PaWin_InitializeWaveFormatExtensible( &renderWaveFormat, outputChannelCount, +                hostOutputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostOutputSampleFormat ),+                nFrameRate, outputChannelMask );++    ZeroMemory(&secondaryRenderDesc, sizeof(DSBUFFERDESC));+    secondaryRenderDesc.dwSize = sizeof(DSBUFFERDESC);+    secondaryRenderDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;+    secondaryRenderDesc.dwBufferBytes = bytesPerOutputBuffer;+    secondaryRenderDesc.lpwfxFormat = (WAVEFORMATEX*)&renderWaveFormat;++    /* note that we don't create a primary buffer here at all */++    hr = paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8( +            inputDevice->lpGUID, outputDevice->lpGUID,+            &captureDesc, &secondaryRenderDesc,+            GetDesktopWindow(), /* see InitOutputBuffer() for a discussion of whether this is a good idea */+            DSSCL_EXCLUSIVE,+            &stream->pDirectSoundFullDuplex8,+            &pCaptureBuffer8,+            &pRenderBuffer8,+            NULL /* pUnkOuter must be NULL */ +        );++    if( hr == DS_OK )+    {+        PA_DEBUG(("DirectSoundFullDuplexCreate succeeded!\n"));++        /* retrieve the pre ds 8 buffer interfaces which are used by the rest of the code */++        hr = IUnknown_QueryInterface( pCaptureBuffer8, &IID_IDirectSoundCaptureBuffer, (LPVOID *)&stream->pDirectSoundInputBuffer );+        +        if( hr == DS_OK )+            hr = IUnknown_QueryInterface( pRenderBuffer8, &IID_IDirectSoundBuffer, (LPVOID *)&stream->pDirectSoundOutputBuffer );++        /* release the ds 8 interfaces, we don't need them */+        IUnknown_Release( pCaptureBuffer8 );+        IUnknown_Release( pRenderBuffer8 );++        if( !stream->pDirectSoundInputBuffer || !stream->pDirectSoundOutputBuffer ){+            /* couldn't get pre ds 8 interfaces for some reason. clean up. */+            if( stream->pDirectSoundInputBuffer )+            {+                IUnknown_Release( stream->pDirectSoundInputBuffer );+                stream->pDirectSoundInputBuffer = NULL;+            }++            if( stream->pDirectSoundOutputBuffer )+            {+                IUnknown_Release( stream->pDirectSoundOutputBuffer );+                stream->pDirectSoundOutputBuffer = NULL;+            }+            +            IUnknown_Release( stream->pDirectSoundFullDuplex8 );+            stream->pDirectSoundFullDuplex8 = NULL;+        }+    }+    else+    {+        PA_DEBUG(("DirectSoundFullDuplexCreate failed. hr=%d\n", hr));+    }++    return hr;+}+#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */+++static HRESULT InitInputBuffer( PaWinDsStream *stream, +                               PaWinDsDeviceInfo *device, +                               PaSampleFormat sampleFormat, +                               unsigned long nFrameRate, +                               WORD nChannels, +                               int bytesPerBuffer, +                               PaWinWaveFormatChannelMask channelMask )+{+    DSCBUFFERDESC  captureDesc;+    PaWinWaveFormat waveFormat;+    HRESULT        result;+    +    if( (result = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( +            device->lpGUID, &stream->pDirectSoundCapture, NULL) ) != DS_OK ){+         ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));+         return result;+    }++    // Setup the secondary buffer description+    ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));+    captureDesc.dwSize = sizeof(DSCBUFFERDESC);+    captureDesc.dwFlags = 0;+    captureDesc.dwBufferBytes = bytesPerBuffer;+    captureDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat;+    +    // Create the capture buffer++    // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX+    PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, +                sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),+                nFrameRate, channelMask );++    if( IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,+                  &captureDesc, &stream->pDirectSoundInputBuffer, NULL) != DS_OK )+    {+        PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, +                PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );++        if ((result = IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,+                    &captureDesc, &stream->pDirectSoundInputBuffer, NULL)) != DS_OK) return result;+    }++    stream->readOffset = 0;  // reset last read position to start of buffer+    return DS_OK;+}+++static HRESULT InitOutputBuffer( PaWinDsStream *stream, PaWinDsDeviceInfo *device, +                                PaSampleFormat sampleFormat, unsigned long nFrameRate, +                                WORD nChannels, int bytesPerBuffer, +                                PaWinWaveFormatChannelMask channelMask )+{+    HRESULT        result;+    HWND           hWnd;+    HRESULT        hr;+    PaWinWaveFormat waveFormat;+    DSBUFFERDESC   primaryDesc;+    DSBUFFERDESC   secondaryDesc;+    +    if( (hr = paWinDsDSoundEntryPoints.DirectSoundCreate( +                device->lpGUID, &stream->pDirectSound, NULL )) != DS_OK ){+        ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));+        return hr;+    }++    // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the+    // applications's window. Also if that window is closed before the Buffer is closed+    // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.)+    // So we will use GetDesktopWindow() which was suggested by Miller Puckette.+    // hWnd = GetForegroundWindow();+    //+    //  FIXME: The example code I have on the net creates a hidden window that+    //      is managed by our code - I think we should do that - one hidden+    //      window for the whole of Pa_DS+    //+    hWnd = GetDesktopWindow();++    // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz.+    // exclusive also prevents unexpected sounds from other apps during a performance.+    if ((hr = IDirectSound_SetCooperativeLevel( stream->pDirectSound,+              hWnd, DSSCL_EXCLUSIVE)) != DS_OK)+    {+        return hr;+    }++    // -----------------------------------------------------------------------+    // Create primary buffer and set format just so we can specify our custom format.+    // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz.+    // Setup the primary buffer description+    ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC));+    primaryDesc.dwSize        = sizeof(DSBUFFERDESC);+    primaryDesc.dwFlags       = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth+    primaryDesc.dwBufferBytes = 0;+    primaryDesc.lpwfxFormat   = NULL;+    // Create the buffer+    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,+                  &primaryDesc, &stream->pDirectSoundPrimaryBuffer, NULL)) != DS_OK)+        goto error;++    // Set the primary buffer's format++    // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX+    PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, +                sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),+                nFrameRate, channelMask );++    if( IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat) != DS_OK )+    {+        PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, +                PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );++        if((result = IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat)) != DS_OK)+            goto error;+    }++    // ----------------------------------------------------------------------+    // Setup the secondary buffer description+    ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC));+    secondaryDesc.dwSize = sizeof(DSBUFFERDESC);+    secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;+    secondaryDesc.dwBufferBytes = bytesPerBuffer;+    secondaryDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat; /* waveFormat contains whatever format was negotiated for the primary buffer above */+    // Create the secondary buffer+    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,+                  &secondaryDesc, &stream->pDirectSoundOutputBuffer, NULL)) != DS_OK)+      goto error;+    +    return DS_OK;++error:++    if( stream->pDirectSoundPrimaryBuffer )+    {+        IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );+        stream->pDirectSoundPrimaryBuffer = NULL;+    }++    return result;+}+++static void CalculateBufferSettings( unsigned long *hostBufferSizeFrames, +                                    unsigned long *pollingPeriodFrames,+                                    int isFullDuplex,+                                    unsigned long suggestedInputLatencyFrames,+                                    unsigned long suggestedOutputLatencyFrames,+                                    double sampleRate, unsigned long userFramesPerBuffer )+{+    unsigned long minimumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MINIMUM_POLLING_PERIOD_SECONDS);+    unsigned long maximumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS);+    unsigned long pollingJitterFrames = (unsigned long)(sampleRate * PA_DS_POLLING_JITTER_SECONDS);+    +    if( userFramesPerBuffer == paFramesPerBufferUnspecified )+    {+        unsigned long targetBufferingLatencyFrames = max( suggestedInputLatencyFrames, suggestedOutputLatencyFrames );++        *pollingPeriodFrames = targetBufferingLatencyFrames / 4;+        if( *pollingPeriodFrames < minimumPollingPeriodFrames )+        {+            *pollingPeriodFrames = minimumPollingPeriodFrames;+        }+        else if( *pollingPeriodFrames > maximumPollingPeriodFrames )+        {+            *pollingPeriodFrames = maximumPollingPeriodFrames;+        }++        *hostBufferSizeFrames = *pollingPeriodFrames +                + max( *pollingPeriodFrames + pollingJitterFrames, targetBufferingLatencyFrames);+    }+    else+    {+        unsigned long targetBufferingLatencyFrames = suggestedInputLatencyFrames;+        if( isFullDuplex )+        {+            /* In full duplex streams we know that the buffer adapter adds userFramesPerBuffer+               extra fixed latency. so we subtract it here as a fixed latency before computing+               the buffer size. being careful not to produce an unrepresentable negative result.+               +               Note: this only works as expected if output latency is greater than input latency.+               Otherwise we use input latency anyway since we do max(in,out).+            */++            if( userFramesPerBuffer < suggestedOutputLatencyFrames )+            {+                unsigned long adjustedSuggestedOutputLatencyFrames = +                        suggestedOutputLatencyFrames - userFramesPerBuffer;++                /* maximum of input and adjusted output suggested latency */+                if( adjustedSuggestedOutputLatencyFrames > targetBufferingLatencyFrames )+                    targetBufferingLatencyFrames = adjustedSuggestedOutputLatencyFrames;+            }+        }+        else+        {+            /* maximum of input and output suggested latency */+            if( suggestedOutputLatencyFrames > suggestedInputLatencyFrames )+                targetBufferingLatencyFrames = suggestedOutputLatencyFrames;+        }   ++        *hostBufferSizeFrames = userFramesPerBuffer +                + max( userFramesPerBuffer + pollingJitterFrames, targetBufferingLatencyFrames);++        *pollingPeriodFrames = max( max(1, userFramesPerBuffer / 4), targetBufferingLatencyFrames / 16 );++        if( *pollingPeriodFrames > maximumPollingPeriodFrames )+        {+            *pollingPeriodFrames = maximumPollingPeriodFrames;+        }+    } +}+++static void CalculatePollingPeriodFrames( unsigned long hostBufferSizeFrames, +                                    unsigned long *pollingPeriodFrames,+                                    double sampleRate, unsigned long userFramesPerBuffer )+{+    unsigned long minimumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MINIMUM_POLLING_PERIOD_SECONDS);+    unsigned long maximumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS);+    unsigned long pollingJitterFrames = (unsigned long)(sampleRate * PA_DS_POLLING_JITTER_SECONDS);++    *pollingPeriodFrames = max( max(1, userFramesPerBuffer / 4), hostBufferSizeFrames / 16 );++    if( *pollingPeriodFrames > maximumPollingPeriodFrames )+    {+        *pollingPeriodFrames = maximumPollingPeriodFrames;+    }+}+++static void SetStreamInfoLatencies( PaWinDsStream *stream, +                                   unsigned long userFramesPerBuffer, +                                   unsigned long pollingPeriodFrames,+                                   double sampleRate )+{+    /* compute the stream info actual latencies based on framesPerBuffer, polling period, hostBufferSizeFrames, +    and the configuration of the buffer processor */++    unsigned long effectiveFramesPerBuffer = (userFramesPerBuffer == paFramesPerBufferUnspecified)+                                             ? pollingPeriodFrames+                                             : userFramesPerBuffer;++    if( stream->bufferProcessor.inputChannelCount > 0 )+    {+        /* stream info input latency is the minimum buffering latency +           (unlike suggested and default which are *maximums*) */+        stream->streamRepresentation.streamInfo.inputLatency =+                (double)(PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)+                    + effectiveFramesPerBuffer) / sampleRate;+    }+    else+    {+        stream->streamRepresentation.streamInfo.inputLatency = 0;+    }++    if( stream->bufferProcessor.outputChannelCount > 0 )+    {+        stream->streamRepresentation.streamInfo.outputLatency =+                (double)(PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)+                    + (stream->hostBufferSizeFrames - effectiveFramesPerBuffer)) / sampleRate;+    }+    else+    {+        stream->streamRepresentation.streamInfo.outputLatency = 0;+    }+}+++/***********************************************************************************/+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */++static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,+                           PaStream** s,+                           const PaStreamParameters *inputParameters,+                           const PaStreamParameters *outputParameters,+                           double sampleRate,+                           unsigned long framesPerBuffer,+                           PaStreamFlags streamFlags,+                           PaStreamCallback *streamCallback,+                           void *userData )+{+    PaError result = paNoError;+    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;+    PaWinDsStream *stream = 0;+    int bufferProcessorIsInitialized = 0;+    int streamRepresentationIsInitialized = 0;+    PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;+    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;+    int inputChannelCount, outputChannelCount;+    PaSampleFormat inputSampleFormat, outputSampleFormat;+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;+    int userRequestedHostInputBufferSizeFrames = 0;+    int userRequestedHostOutputBufferSizeFrames = 0;+    unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames;+    PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;+    PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;+    unsigned long pollingPeriodFrames = 0;++    if( inputParameters )+    {+        inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];+        inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;++        inputChannelCount = inputParameters->channelCount;+        inputSampleFormat = inputParameters->sampleFormat;+        suggestedInputLatencyFrames = (unsigned long)(inputParameters->suggestedLatency * sampleRate);++        /* IDEA: the following 3 checks could be performed by default by pa_front+            unless some flag indicated otherwise */+            +        /* unless alternate device specification is supported, reject the use of+            paUseHostApiSpecificDeviceSpecification */+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )+            return paInvalidDevice;++        /* check that input device can support inputChannelCount */+        if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown+                && inputChannelCount > inputDeviceInfo->maxInputChannels )+            return paInvalidChannelCount;+            +        /* validate hostApiSpecificStreamInfo */+        inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;+		result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );+		if( result != paNoError ) return result;++        if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )+            userRequestedHostInputBufferSizeFrames = inputStreamInfo->framesPerBuffer;++        if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseChannelMask )+            inputChannelMask = inputStreamInfo->channelMask;+        else+            inputChannelMask = PaWin_DefaultChannelMask( inputChannelCount );+    }+    else+    {+        inputChannelCount = 0;+		inputSampleFormat = 0;+        suggestedInputLatencyFrames = 0;+    }+++    if( outputParameters )+    {+        outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];+        outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;++        outputChannelCount = outputParameters->channelCount;+        outputSampleFormat = outputParameters->sampleFormat;+        suggestedOutputLatencyFrames = (unsigned long)(outputParameters->suggestedLatency * sampleRate);++        /* unless alternate device specification is supported, reject the use of+            paUseHostApiSpecificDeviceSpecification */+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )+            return paInvalidDevice;++        /* check that output device can support outputChannelCount */+        if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown+                && outputChannelCount > outputDeviceInfo->maxOutputChannels )+            return paInvalidChannelCount;++        /* validate hostApiSpecificStreamInfo */+        outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;+		result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );+		if( result != paNoError ) return result;   ++        if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )+            userRequestedHostOutputBufferSizeFrames = outputStreamInfo->framesPerBuffer;++        if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseChannelMask )+            outputChannelMask = outputStreamInfo->channelMask;+        else+            outputChannelMask = PaWin_DefaultChannelMask( outputChannelCount );+    }+    else+    {+        outputChannelCount = 0;+		outputSampleFormat = 0;+        suggestedOutputLatencyFrames = 0;+    }++    /*+        If low level host buffer size is specified for both input and output+        the current code requires the sizes to match.+    */++    if( (userRequestedHostInputBufferSizeFrames > 0 && userRequestedHostOutputBufferSizeFrames > 0)+            && userRequestedHostInputBufferSizeFrames != userRequestedHostOutputBufferSizeFrames )+        return paIncompatibleHostApiSpecificStreamInfo;++++    /*+        IMPLEMENT ME:++        ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() )++            - check that input device can support inputSampleFormat, or that+                we have the capability to convert from outputSampleFormat to+                a native format++            - check that output device can support outputSampleFormat, or that+                we have the capability to convert from outputSampleFormat to+                a native format++            - if a full duplex stream is requested, check that the combination+                of input and output parameters is supported++            - check that the device supports sampleRate++            - alter sampleRate to a close allowable rate if possible / necessary++            - validate suggestedInputLatency and suggestedOutputLatency parameters,+                use default values where necessary+    */+++    /* validate platform specific flags */+    if( (streamFlags & paPlatformSpecificFlags) != 0 )+        return paInvalidFlag; /* unexpected platform specific flag */+++    stream = (PaWinDsStream*)PaUtil_AllocateMemory( sizeof(PaWinDsStream) );+    if( !stream )+    {+        result = paInsufficientMemory;+        goto error;+    }++    memset( stream, 0, sizeof(PaWinDsStream) ); /* initialize all stream variables to 0 */++    if( streamCallback )+    {+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,+                                               &winDsHostApi->callbackStreamInterface, streamCallback, userData );+    }+    else+    {+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,+                                               &winDsHostApi->blockingStreamInterface, streamCallback, userData );+    }+    +    streamRepresentationIsInitialized = 1;++    stream->streamFlags = streamFlags;++    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );+++    if( inputParameters )+    {+        /* IMPLEMENT ME - establish which  host formats are available */+        PaSampleFormat nativeInputFormats = paInt16;+        /* PaSampleFormat nativeFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; */++        hostInputSampleFormat =+            PaUtil_SelectClosestAvailableFormat( nativeInputFormats, inputParameters->sampleFormat );+    }+	else+	{+		hostInputSampleFormat = 0;+	}++    if( outputParameters )+    {+        /* IMPLEMENT ME - establish which  host formats are available */+        PaSampleFormat nativeOutputFormats = paInt16;+        /* PaSampleFormat nativeOutputFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; */++        hostOutputSampleFormat =+            PaUtil_SelectClosestAvailableFormat( nativeOutputFormats, outputParameters->sampleFormat );+    }+    else+	{+		hostOutputSampleFormat = 0;+	}++    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,+                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,+                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,+                    sampleRate, streamFlags, framesPerBuffer,+                    0, /* ignored in paUtilVariableHostBufferSizePartialUsageAllowed mode. */+                /* This next mode is required because DS can split the host buffer when it wraps around. */+                    paUtilVariableHostBufferSizePartialUsageAllowed,+                    streamCallback, userData );+    if( result != paNoError )+        goto error;++    bufferProcessorIsInitialized = 1;++   +/* DirectSound specific initialization */ +    {+        HRESULT          hr;+        unsigned long    integerSampleRate = (unsigned long) (sampleRate + 0.5);+        +        stream->processingCompleted = CreateEvent( NULL, /* bManualReset = */ TRUE, /* bInitialState = */ FALSE, NULL );+        if( stream->processingCompleted == NULL )+        {+            result = paInsufficientMemory;+            goto error;+        }++#ifdef PA_WIN_DS_USE_WMME_TIMER+        stream->timerID = 0;+#endif++#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT+        stream->waitableTimer = (HANDLE)CreateWaitableTimer( 0, FALSE, NULL );+        if( stream->waitableTimer == NULL )+        {+            result = paUnanticipatedHostError;+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );+            goto error;+        }+#endif++#ifndef PA_WIN_DS_USE_WMME_TIMER+		stream->processingThreadCompleted = CreateEvent( NULL, /* bManualReset = */ TRUE, /* bInitialState = */ FALSE, NULL );+        if( stream->processingThreadCompleted == NULL )+        {+            result = paUnanticipatedHostError;+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );+            goto error;+        }+#endif++        /* set up i/o parameters */++        if( userRequestedHostInputBufferSizeFrames > 0 || userRequestedHostOutputBufferSizeFrames > 0 )+        {+            /* use low level parameters */++            /* since we use the same host buffer size for input and output+               we choose the highest user specified value.+            */+            stream->hostBufferSizeFrames = max( userRequestedHostInputBufferSizeFrames, userRequestedHostOutputBufferSizeFrames );++            CalculatePollingPeriodFrames( +                    stream->hostBufferSizeFrames, &pollingPeriodFrames,+                    sampleRate, framesPerBuffer );+        }+        else+        {+            CalculateBufferSettings( &stream->hostBufferSizeFrames, &pollingPeriodFrames,+                    /* isFullDuplex = */ (inputParameters && outputParameters),+                    suggestedInputLatencyFrames,+                    suggestedOutputLatencyFrames, +                    sampleRate, framesPerBuffer );+        }++        stream->pollingPeriodSeconds = pollingPeriodFrames / sampleRate;++        DBUG(("DirectSound host buffer size frames: %d, polling period seconds: %f, @ sr: %f\n", +                stream->hostBufferSizeFrames, stream->pollingPeriodSeconds, sampleRate ));+++        /* ------------------ OUTPUT */+        if( outputParameters )+        {+            LARGE_INTEGER  counterFrequency;++            /*+            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ outputParameters->device ];+            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", outputParameters->device));+            */+            +            int sampleSizeBytes = Pa_GetSampleSize(hostOutputSampleFormat);+            stream->outputFrameSizeBytes = outputParameters->channelCount * sampleSizeBytes;++            stream->outputBufferSizeBytes = stream->hostBufferSizeFrames * stream->outputFrameSizeBytes;+            if( stream->outputBufferSizeBytes < DSBSIZE_MIN )+            {+                result = paBufferTooSmall;+                goto error;+            }+            else if( stream->outputBufferSizeBytes > DSBSIZE_MAX )+            {+                result = paBufferTooBig;+                goto error;+            }++            /* Calculate value used in latency calculation to avoid real-time divides. */+            stream->secondsPerHostByte = 1.0 /+                (stream->bufferProcessor.bytesPerHostOutputSample *+                outputChannelCount * sampleRate);++            stream->outputIsRunning = FALSE;+            stream->outputUnderflowCount = 0;+            +            /* perfCounterTicksPerBuffer is used by QueryOutputSpace for overflow detection */+            if( QueryPerformanceFrequency( &counterFrequency ) )+            {+                stream->perfCounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * stream->hostBufferSizeFrames) / integerSampleRate;+            }+            else+            {+                stream->perfCounterTicksPerBuffer.QuadPart = 0;+            }+        }++        /* ------------------ INPUT */+        if( inputParameters )+        {+            /*+            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ inputParameters->device ];+            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", inputParameters->device));+            */+            +            int sampleSizeBytes = Pa_GetSampleSize(hostInputSampleFormat);+            stream->inputFrameSizeBytes = inputParameters->channelCount * sampleSizeBytes;++            stream->inputBufferSizeBytes = stream->hostBufferSizeFrames * stream->inputFrameSizeBytes;+            if( stream->inputBufferSizeBytes < DSBSIZE_MIN )+            {+                result = paBufferTooSmall;+                goto error;+            }+            else if( stream->inputBufferSizeBytes > DSBSIZE_MAX )+            {+                result = paBufferTooBig;+                goto error;+            }+        }++        /* open/create the DirectSound buffers */++        /* interface ptrs should be zeroed when stream is zeroed. */+        assert( stream->pDirectSoundCapture == NULL );+        assert( stream->pDirectSoundInputBuffer == NULL );+        assert( stream->pDirectSound == NULL );+        assert( stream->pDirectSoundPrimaryBuffer == NULL );+        assert( stream->pDirectSoundOutputBuffer == NULL );+        ++        if( inputParameters && outputParameters )+        {+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+            /* try to use the full-duplex DX8 API to create the buffers.+                if that fails we fall back to the half-duplex API below */++            hr = InitFullDuplexInputOutputBuffers( stream,+                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],+                                       hostInputSampleFormat,+                                       (WORD)inputParameters->channelCount, stream->inputBufferSizeBytes,+                                       inputChannelMask,+                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],+                                       hostOutputSampleFormat,+                                       (WORD)outputParameters->channelCount, stream->outputBufferSizeBytes,+                                       outputChannelMask,+                                       integerSampleRate+                                        );+            DBUG(("InitFullDuplexInputOutputBuffers() returns %x\n", hr));+            /* ignore any error returned by InitFullDuplexInputOutputBuffers. +                we retry opening the buffers below */+#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */+        }++        /*  create half duplex buffers. also used for full-duplex streams which didn't +            succeed when using the full duplex API. that could happen because+            DX8 or greater isnt installed, the i/o devices aren't the same +            physical device. etc.+        */++        if( outputParameters && !stream->pDirectSoundOutputBuffer )+        {+            hr = InitOutputBuffer( stream,+                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],+                                       hostOutputSampleFormat,+                                       integerSampleRate,+                                       (WORD)outputParameters->channelCount, stream->outputBufferSizeBytes,+                                       outputChannelMask );+            DBUG(("InitOutputBuffer() returns %x\n", hr));+            if( hr != DS_OK )+            {+                result = paUnanticipatedHostError;+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );+                goto error;+            }+        }++        if( inputParameters && !stream->pDirectSoundInputBuffer )+        {+            hr = InitInputBuffer( stream,+                                      (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],+                                      hostInputSampleFormat,+                                      integerSampleRate,+                                      (WORD)inputParameters->channelCount, stream->inputBufferSizeBytes,+                                      inputChannelMask );+            DBUG(("InitInputBuffer() returns %x\n", hr));+            if( hr != DS_OK )+            {+                ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));+                result = paUnanticipatedHostError;+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );+                goto error;+            }+        }+    }++    SetStreamInfoLatencies( stream, framesPerBuffer, pollingPeriodFrames, sampleRate );++    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;++    *s = (PaStream*)stream;++    return result;++error:+    if( stream )+    {+        if( stream->processingCompleted != NULL )+            CloseHandle( stream->processingCompleted );++#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT+        if( stream->waitableTimer != NULL )+            CloseHandle( stream->waitableTimer );+#endif++#ifndef PA_WIN_DS_USE_WMME_TIMER+        if( stream->processingThreadCompleted != NULL )+            CloseHandle( stream->processingThreadCompleted );+#endif++        if( stream->pDirectSoundOutputBuffer )+        {+            IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );+            IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );+            stream->pDirectSoundOutputBuffer = NULL;+        }++        if( stream->pDirectSoundPrimaryBuffer )+        {+            IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );+            stream->pDirectSoundPrimaryBuffer = NULL;+        }++        if( stream->pDirectSoundInputBuffer )+        {+            IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );+            IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );+            stream->pDirectSoundInputBuffer = NULL;+        }++        if( stream->pDirectSoundCapture )+        {+            IDirectSoundCapture_Release( stream->pDirectSoundCapture );+            stream->pDirectSoundCapture = NULL;+        }++        if( stream->pDirectSound )+        {+            IDirectSound_Release( stream->pDirectSound );+            stream->pDirectSound = NULL;+        }++#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+        if( stream->pDirectSoundFullDuplex8 )+        {+            IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );+            stream->pDirectSoundFullDuplex8 = NULL;+        }+#endif+        if( bufferProcessorIsInitialized )+            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );++        if( streamRepresentationIsInitialized )+            PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );++        PaUtil_FreeMemory( stream );+    }++    return result;+}+++/************************************************************************************+ * Determine how much space can be safely written to in DS buffer.+ * Detect underflows and overflows.+ * Does not allow writing into safety gap maintained by DirectSound.+ */+static HRESULT QueryOutputSpace( PaWinDsStream *stream, long *bytesEmpty )+{+    HRESULT hr;+    DWORD   playCursor;+    DWORD   writeCursor;+    long    numBytesEmpty;+    long    playWriteGap;+    // Query to see how much room is in buffer.+    hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,+            &playCursor, &writeCursor );+    if( hr != DS_OK )+    {+        return hr;+    }++    // Determine size of gap between playIndex and WriteIndex that we cannot write into.+    playWriteGap = writeCursor - playCursor;+    if( playWriteGap < 0 ) playWriteGap += stream->outputBufferSizeBytes; // unwrap++    /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */+    /* Attempt to detect playCursor wrap-around and correct it. */+    if( stream->outputIsRunning && (stream->perfCounterTicksPerBuffer.QuadPart != 0) )+    {+        /* How much time has elapsed since last check. */+        LARGE_INTEGER   currentTime;+        LARGE_INTEGER   elapsedTime;+        long            bytesPlayed;+        long            bytesExpected;+        long            buffersWrapped;++        QueryPerformanceCounter( &currentTime );+        elapsedTime.QuadPart = currentTime.QuadPart - stream->previousPlayTime.QuadPart;+        stream->previousPlayTime = currentTime;++        /* How many bytes does DirectSound say have been played. */+        bytesPlayed = playCursor - stream->previousPlayCursor;+        if( bytesPlayed < 0 ) bytesPlayed += stream->outputBufferSizeBytes; // unwrap+        stream->previousPlayCursor = playCursor;++        /* Calculate how many bytes we would have expected to been played by now. */+        bytesExpected = (long) ((elapsedTime.QuadPart * stream->outputBufferSizeBytes) / stream->perfCounterTicksPerBuffer.QuadPart);+        buffersWrapped = (bytesExpected - bytesPlayed) / stream->outputBufferSizeBytes;+        if( buffersWrapped > 0 )+        {+            playCursor += (buffersWrapped * stream->outputBufferSizeBytes);+            bytesPlayed += (buffersWrapped * stream->outputBufferSizeBytes);+        }+    }+    numBytesEmpty = playCursor - stream->outputBufferWriteOffsetBytes;+    if( numBytesEmpty < 0 ) numBytesEmpty += stream->outputBufferSizeBytes; // unwrap offset++    /* Have we underflowed? */+    if( numBytesEmpty > (stream->outputBufferSizeBytes - playWriteGap) )+    {+        if( stream->outputIsRunning )+        {+            stream->outputUnderflowCount += 1;+        }++        /*+            From MSDN:+                The write cursor indicates the position at which it is safe  +            to write new data to the buffer. The write cursor always leads the+            play cursor, typically by about 15 milliseconds' worth of audio+            data.+                It is always safe to change data that is behind the position +            indicated by the lpdwCurrentPlayCursor parameter.+        */++        stream->outputBufferWriteOffsetBytes = writeCursor;+        numBytesEmpty = stream->outputBufferSizeBytes - playWriteGap;+    }+    *bytesEmpty = numBytesEmpty;+    return hr;+}++/***********************************************************************************/+static int TimeSlice( PaWinDsStream *stream )+{+    long              numFrames = 0;+    long              bytesEmpty = 0;+    long              bytesFilled = 0;+    long              bytesToXfer = 0;+    long              framesToXfer = 0; /* the number of frames we'll process this tick */+    long              numInFramesReady = 0;+    long              numOutFramesReady = 0;+    long              bytesProcessed;+    HRESULT           hresult;+    double            outputLatency = 0;+    double            inputLatency = 0;+    PaStreamCallbackTimeInfo timeInfo = {0,0,0};+    +/* Input */+    LPBYTE            lpInBuf1 = NULL;+    LPBYTE            lpInBuf2 = NULL;+    DWORD             dwInSize1 = 0;+    DWORD             dwInSize2 = 0;+/* Output */+    LPBYTE            lpOutBuf1 = NULL;+    LPBYTE            lpOutBuf2 = NULL;+    DWORD             dwOutSize1 = 0;+    DWORD             dwOutSize2 = 0;++    /* How much input data is available? */+    if( stream->bufferProcessor.inputChannelCount > 0 )+    {+        HRESULT hr;+        DWORD capturePos;+        DWORD readPos;+        long  filled = 0;+        // Query to see how much data is in buffer.+        // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly+        // so let's pass a pointer just to be safe.+        hr = IDirectSoundCaptureBuffer_GetCurrentPosition( stream->pDirectSoundInputBuffer, &capturePos, &readPos );+        if( hr == DS_OK )+        {+            filled = readPos - stream->readOffset;+            if( filled < 0 ) filled += stream->inputBufferSizeBytes; // unwrap offset+            bytesFilled = filled;++            inputLatency = ((double)bytesFilled) * stream->secondsPerHostByte;+        }+            // FIXME: what happens if IDirectSoundCaptureBuffer_GetCurrentPosition fails?++        framesToXfer = numInFramesReady = bytesFilled / stream->inputFrameSizeBytes; ++        /** @todo Check for overflow */+    }++    /* How much output room is available? */+    if( stream->bufferProcessor.outputChannelCount > 0 )+    {+        UINT previousUnderflowCount = stream->outputUnderflowCount;+        QueryOutputSpace( stream, &bytesEmpty );+        framesToXfer = numOutFramesReady = bytesEmpty / stream->outputFrameSizeBytes;++        /* Check for underflow */+		/* FIXME QueryOutputSpace should not adjust underflow count as a side effect. +			A query function should be a const operator on the stream and return a flag on underflow. */+        if( stream->outputUnderflowCount != previousUnderflowCount )+            stream->callbackFlags |= paOutputUnderflow;++        /* We are about to compute audio into the first byte of empty space in the output buffer.+           This audio will reach the DAC after all of the current (non-empty) audio+           in the buffer has played. Therefore the output time is the current time+           plus the time it takes to play the non-empty bytes in the buffer,+           computed here:+        */+        outputLatency = ((double)(stream->outputBufferSizeBytes - bytesEmpty)) * stream->secondsPerHostByte;+    }++    /* if it's a full duplex stream, set framesToXfer to the minimum of input and output frames ready */+    if( stream->bufferProcessor.inputChannelCount > 0 && stream->bufferProcessor.outputChannelCount > 0 )+    {+        framesToXfer = (numOutFramesReady < numInFramesReady) ? numOutFramesReady : numInFramesReady;+    }++    if( framesToXfer > 0 )+    {+        PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );++    /* The outputBufferDacTime parameter should indicates the time at which+        the first sample of the output buffer is heard at the DACs. */+        timeInfo.currentTime = PaUtil_GetTime();++        PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, stream->callbackFlags );+        stream->callbackFlags = 0;+        +    /* Input */+        if( stream->bufferProcessor.inputChannelCount > 0 )+        {+            timeInfo.inputBufferAdcTime = timeInfo.currentTime - inputLatency; ++            bytesToXfer = framesToXfer * stream->inputFrameSizeBytes;+            hresult = IDirectSoundCaptureBuffer_Lock ( stream->pDirectSoundInputBuffer,+                stream->readOffset, bytesToXfer,+                (void **) &lpInBuf1, &dwInSize1,+                (void **) &lpInBuf2, &dwInSize2, 0);+            if (hresult != DS_OK)+            {+                ERR_RPT(("DirectSound IDirectSoundCaptureBuffer_Lock failed, hresult = 0x%x\n",hresult));+                /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */+                PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */+                stream->callbackResult = paComplete;+                goto error2;+            }++            numFrames = dwInSize1 / stream->inputFrameSizeBytes;+            PaUtil_SetInputFrameCount( &stream->bufferProcessor, numFrames );+            PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf1, 0 );+        /* Is input split into two regions. */+            if( dwInSize2 > 0 )+            {+                numFrames = dwInSize2 / stream->inputFrameSizeBytes;+                PaUtil_Set2ndInputFrameCount( &stream->bufferProcessor, numFrames );+                PaUtil_Set2ndInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf2, 0 );+            }+        }++    /* Output */+        if( stream->bufferProcessor.outputChannelCount > 0 )+        {+            /*+			We don't currently add outputLatency here because it appears to produce worse+			results than not adding it. Need to do more testing to verify this.+            */+            /* timeInfo.outputBufferDacTime = timeInfo.currentTime + outputLatency; */+            timeInfo.outputBufferDacTime = timeInfo.currentTime;++            bytesToXfer = framesToXfer * stream->outputFrameSizeBytes;+            hresult = IDirectSoundBuffer_Lock ( stream->pDirectSoundOutputBuffer,+                stream->outputBufferWriteOffsetBytes, bytesToXfer,+                (void **) &lpOutBuf1, &dwOutSize1,+                (void **) &lpOutBuf2, &dwOutSize2, 0);+            if (hresult != DS_OK)+            {+                ERR_RPT(("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n",hresult));+                /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */+                PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */+                stream->callbackResult = paComplete;+                goto error1;+            }++            numFrames = dwOutSize1 / stream->outputFrameSizeBytes;+            PaUtil_SetOutputFrameCount( &stream->bufferProcessor, numFrames );+            PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf1, 0 );++        /* Is output split into two regions. */+            if( dwOutSize2 > 0 )+            {+                numFrames = dwOutSize2 / stream->outputFrameSizeBytes;+                PaUtil_Set2ndOutputFrameCount( &stream->bufferProcessor, numFrames );+                PaUtil_Set2ndInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf2, 0 );+            }+        }++        numFrames = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &stream->callbackResult );+        stream->framesWritten += numFrames;+        +        if( stream->bufferProcessor.outputChannelCount > 0 )+        {+        /* FIXME: an underflow could happen here */++        /* Update our buffer offset and unlock sound buffer */+            bytesProcessed = numFrames * stream->outputFrameSizeBytes;+            stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + bytesProcessed) % stream->outputBufferSizeBytes;+            IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2);+        }++error1:+        if( stream->bufferProcessor.inputChannelCount > 0 )+        {+        /* FIXME: an overflow could happen here */++        /* Update our buffer offset and unlock sound buffer */+            bytesProcessed = numFrames * stream->inputFrameSizeBytes;+            stream->readOffset = (stream->readOffset + bytesProcessed) % stream->inputBufferSizeBytes;+            IDirectSoundCaptureBuffer_Unlock( stream->pDirectSoundInputBuffer, lpInBuf1, dwInSize1, lpInBuf2, dwInSize2);+        }+error2:++        PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, numFrames );        +    }++    if( stream->callbackResult == paComplete && !PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )+    {+        /* don't return completed until the buffer processor has been drained */+        return paContinue;+    }+    else+    {+        return stream->callbackResult;+    }+}+/*******************************************************************/++static HRESULT ZeroAvailableOutputSpace( PaWinDsStream *stream )+{+    HRESULT hr;+    LPBYTE lpbuf1 = NULL;+    LPBYTE lpbuf2 = NULL;+    DWORD dwsize1 = 0;+    DWORD dwsize2 = 0;+    long  bytesEmpty;+    hr = QueryOutputSpace( stream, &bytesEmpty );+    if (hr != DS_OK) return hr;+    if( bytesEmpty == 0 ) return DS_OK;+    // Lock free space in the DS+    hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, stream->outputBufferWriteOffsetBytes,+                                    bytesEmpty, (void **) &lpbuf1, &dwsize1,+                                    (void **) &lpbuf2, &dwsize2, 0);+    if (hr == DS_OK)+    {+        // Copy the buffer into the DS+        ZeroMemory(lpbuf1, dwsize1);+        if(lpbuf2 != NULL)+        {+            ZeroMemory(lpbuf2, dwsize2);+        }+        // Update our buffer offset and unlock sound buffer+        stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + dwsize1 + dwsize2) % stream->outputBufferSizeBytes;+        IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2);++        stream->finalZeroBytesWritten += dwsize1 + dwsize2;+    }+    return hr;+}+++static void CALLBACK TimerCallback(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2)+{+    PaWinDsStream *stream;+    int isFinished = 0;++    /* suppress unused variable warnings */+    (void) uID;+    (void) uMsg;+    (void) dw1;+    (void) dw2;+    +    stream = (PaWinDsStream *) dwUser;+    if( stream == NULL ) return;++    if( stream->isActive )+    {+        if( stream->abortProcessing )+        {+            isFinished = 1;+        }+        else if( stream->stopProcessing )+        {+            if( stream->bufferProcessor.outputChannelCount > 0 )+            {+                ZeroAvailableOutputSpace( stream );+                if( stream->finalZeroBytesWritten >= stream->outputBufferSizeBytes )+                {+                    /* once we've flushed the whole output buffer with zeros we know all data has been played */+                    isFinished = 1;+                }+            }+            else+            {+                isFinished = 1;+            }+        }+        else+        {+            int callbackResult = TimeSlice( stream );+            if( callbackResult != paContinue )+            {+                /* FIXME implement handling of paComplete and paAbort if possible +                   At the moment this should behave as if paComplete was called and +                   flush the buffer.+                */++                stream->stopProcessing = 1;+            }+        }++        if( isFinished )+        {+            if( stream->streamRepresentation.streamFinishedCallback != 0 )+                stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );++            stream->isActive = 0; /* don't set this until the stream really is inactive */+            SetEvent( stream->processingCompleted );+        }+    }+}++#ifndef PA_WIN_DS_USE_WMME_TIMER++#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT++static void CALLBACK WaitableTimerAPCProc(+   LPVOID lpArg,               // Data value+   DWORD dwTimerLowValue,      // Timer low value+   DWORD dwTimerHighValue )    // Timer high value++{+    (void)dwTimerLowValue;+    (void)dwTimerHighValue;++    TimerCallback( 0, 0, (DWORD_PTR)lpArg, 0, 0 );+}++#endif /* PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT */+++PA_THREAD_FUNC ProcessingThreadProc( void *pArg )+{+    PaWinDsStream *stream = (PaWinDsStream *)pArg;+    LARGE_INTEGER dueTime;+    int timerPeriodMs;++    timerPeriodMs = (int)(stream->pollingPeriodSeconds * MSECS_PER_SECOND);+    if( timerPeriodMs < 1 )+        timerPeriodMs = 1;++#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT+    assert( stream->waitableTimer != NULL );++    /* invoke first timeout immediately */+    dueTime.LowPart = timerPeriodMs * 1000 * 10;+    dueTime.HighPart = 0;++    /* tick using waitable timer */+    if( SetWaitableTimer( stream->waitableTimer, &dueTime, timerPeriodMs, WaitableTimerAPCProc, pArg, FALSE ) != 0 )+    {+        DWORD wfsoResult = 0;+        do+        {+            /* wait for processingCompleted to be signaled or our timer APC to be called */+            wfsoResult = WaitForSingleObjectEx( stream->processingCompleted, timerPeriodMs * 10, /* alertable = */ TRUE );++        }while( wfsoResult == WAIT_TIMEOUT || wfsoResult == WAIT_IO_COMPLETION );+    }++    CancelWaitableTimer( stream->waitableTimer );++#else++    /* tick using WaitForSingleObject timout */+    while ( WaitForSingleObject( stream->processingCompleted, timerPeriodMs ) == WAIT_TIMEOUT )+    {+        TimerCallback( 0, 0, (DWORD_PTR)pArg, 0, 0 );+    }+#endif /* PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT */++    SetEvent( stream->processingThreadCompleted );++    return 0;+}++#endif /* !PA_WIN_DS_USE_WMME_TIMER */++/***********************************************************************************+    When CloseStream() is called, the multi-api layer ensures that+    the stream has already been stopped or aborted.+*/+static PaError CloseStream( PaStream* s )+{+    PaError result = paNoError;+    PaWinDsStream *stream = (PaWinDsStream*)s;++    CloseHandle( stream->processingCompleted );++#ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT+    if( stream->waitableTimer != NULL )+        CloseHandle( stream->waitableTimer );+#endif++#ifndef PA_WIN_DS_USE_WMME_TIMER+	CloseHandle( stream->processingThreadCompleted );+#endif++    // Cleanup the sound buffers+    if( stream->pDirectSoundOutputBuffer )+    {+        IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );+        IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );+        stream->pDirectSoundOutputBuffer = NULL;+    }++    if( stream->pDirectSoundPrimaryBuffer )+    {+        IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );+        stream->pDirectSoundPrimaryBuffer = NULL;+    }++    if( stream->pDirectSoundInputBuffer )+    {+        IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );+        IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );+        stream->pDirectSoundInputBuffer = NULL;+    }++    if( stream->pDirectSoundCapture )+    {+        IDirectSoundCapture_Release( stream->pDirectSoundCapture );+        stream->pDirectSoundCapture = NULL;+    }++    if( stream->pDirectSound )+    {+        IDirectSound_Release( stream->pDirectSound );+        stream->pDirectSound = NULL;+    }++#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+    if( stream->pDirectSoundFullDuplex8 )+    {+        IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );+        stream->pDirectSoundFullDuplex8 = NULL;+    }+#endif++    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );+    PaUtil_FreeMemory( stream );++    return result;+}++/***********************************************************************************/+static HRESULT ClearOutputBuffer( PaWinDsStream *stream )+{+    PaError          result = paNoError;+    unsigned char*   pDSBuffData;+    DWORD            dwDataLen;+    HRESULT          hr;++    hr = IDirectSoundBuffer_SetCurrentPosition( stream->pDirectSoundOutputBuffer, 0 );+    DBUG(("PaHost_ClearOutputBuffer: IDirectSoundBuffer_SetCurrentPosition returned = 0x%X.\n", hr));+    if( hr != DS_OK )+        return hr;++    // Lock the DS buffer+    if ((hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, 0, stream->outputBufferSizeBytes, (LPVOID*)&pDSBuffData,+                                           &dwDataLen, NULL, 0, 0)) != DS_OK )+        return hr;++    // Zero the DS buffer+    ZeroMemory(pDSBuffData, dwDataLen);+    // Unlock the DS buffer+    if ((hr = IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK)+        return hr;+    +    // Let DSound set the starting write position because if we set it to zero, it looks like the+    // buffer is full to begin with. This causes a long pause before sound starts when using large buffers.+    if ((hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,+            &stream->previousPlayCursor, &stream->outputBufferWriteOffsetBytes )) != DS_OK)+        return hr;++    /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */++    return DS_OK;+}++static PaError StartStream( PaStream *s )+{+    PaError          result = paNoError;+    PaWinDsStream   *stream = (PaWinDsStream*)s;+    HRESULT          hr;+        +    stream->callbackResult = paContinue;+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );+    +    ResetEvent( stream->processingCompleted );++#ifndef PA_WIN_DS_USE_WMME_TIMER+	ResetEvent( stream->processingThreadCompleted );+#endif++    if( stream->bufferProcessor.inputChannelCount > 0 )+    {+        // Start the buffer capture+        if( stream->pDirectSoundInputBuffer != NULL ) // FIXME: not sure this check is necessary+        {+            hr = IDirectSoundCaptureBuffer_Start( stream->pDirectSoundInputBuffer, DSCBSTART_LOOPING );+        }++        DBUG(("StartStream: DSW_StartInput returned = 0x%X.\n", hr));+        if( hr != DS_OK )+        {+            result = paUnanticipatedHostError;+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );+            goto error;+        }+    }++    stream->framesWritten = 0;+    stream->callbackFlags = 0;++    stream->abortProcessing = 0;+    stream->stopProcessing = 0;++    if( stream->bufferProcessor.outputChannelCount > 0 )+    {+        QueryPerformanceCounter( &stream->previousPlayTime );+        stream->finalZeroBytesWritten = 0;++        hr = ClearOutputBuffer( stream );+        if( hr != DS_OK )+        {+            result = paUnanticipatedHostError;+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );+            goto error;+        }++        if( stream->streamRepresentation.streamCallback && (stream->streamFlags & paPrimeOutputBuffersUsingStreamCallback) )+        {+            stream->callbackFlags = paPrimingOutput;++            TimeSlice( stream );+            /* we ignore the return value from TimeSlice here and start the stream as usual.+                The first timer callback will detect if the callback has completed. */++            stream->callbackFlags = 0;+        }++        // Start the buffer playback in a loop.+        if( stream->pDirectSoundOutputBuffer != NULL ) // FIXME: not sure this needs to be checked here+        {+            hr = IDirectSoundBuffer_Play( stream->pDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING );+            DBUG(("PaHost_StartOutput: IDirectSoundBuffer_Play returned = 0x%X.\n", hr));+            if( hr != DS_OK )+            {+                result = paUnanticipatedHostError;+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );+                goto error;+            }+            stream->outputIsRunning = TRUE;+        }+    }++    if( stream->streamRepresentation.streamCallback )+    {+        TIMECAPS timecaps;+        int timerPeriodMs = (int)(stream->pollingPeriodSeconds * MSECS_PER_SECOND);+        if( timerPeriodMs < 1 )+            timerPeriodMs = 1;++        /* set windows scheduler granularity only as fine as needed, no finer */+        /* Although this is not fully documented by MS, it appears that+           timeBeginPeriod() affects the scheduling granulatity of all timers+           including Waitable Timer Objects. So we always call timeBeginPeriod, whether+           we're using an MM timer callback via timeSetEvent or not.+        */+        assert( stream->systemTimerResolutionPeriodMs == 0 );+        if( timeGetDevCaps( &timecaps, sizeof(TIMECAPS) ) == MMSYSERR_NOERROR && timecaps.wPeriodMin > 0 )+        {+            /* aim for resolution 4 times higher than polling rate */+            stream->systemTimerResolutionPeriodMs = (UINT)((stream->pollingPeriodSeconds * MSECS_PER_SECOND) * .25);+            if( stream->systemTimerResolutionPeriodMs < timecaps.wPeriodMin )+                stream->systemTimerResolutionPeriodMs = timecaps.wPeriodMin;+            if( stream->systemTimerResolutionPeriodMs > timecaps.wPeriodMax )+                stream->systemTimerResolutionPeriodMs = timecaps.wPeriodMax;++            if( timeBeginPeriod( stream->systemTimerResolutionPeriodMs ) != MMSYSERR_NOERROR )+                stream->systemTimerResolutionPeriodMs = 0; /* timeBeginPeriod failed, so we don't need to call timeEndPeriod() later */+        }+++#ifdef PA_WIN_DS_USE_WMME_TIMER+        /* Create timer that will wake us up so we can fill the DSound buffer. */+        /* We have deprecated timeSetEvent because all MM timer callbacks+           are serialised onto a single thread. Which creates problems with multiple+           PA streams, or when also using timers for other time critical tasks+        */+        stream->timerID = timeSetEvent( timerPeriodMs, stream->systemTimerResolutionPeriodMs, (LPTIMECALLBACK) TimerCallback,+                                             (DWORD_PTR) stream, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS );+    +        if( stream->timerID == 0 )+        {+            stream->isActive = 0;+            result = paUnanticipatedHostError;+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );+            goto error;+        }+#else+		/* Create processing thread which calls TimerCallback */++		stream->processingThread = CREATE_THREAD( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId );+        if( !stream->processingThread )+        {+            result = paUnanticipatedHostError;+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );+            goto error;+        }++        if( !SetThreadPriority( stream->processingThread, THREAD_PRIORITY_TIME_CRITICAL ) )+        {+            result = paUnanticipatedHostError;+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );+            goto error;+        }+#endif+    }++    stream->isActive = 1;+    stream->isStarted = 1;++    assert( result == paNoError );+    return result;++error:++    if( stream->pDirectSoundOutputBuffer != NULL && stream->outputIsRunning )+        IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );+    stream->outputIsRunning = FALSE;++#ifndef PA_WIN_DS_USE_WMME_TIMER+    if( stream->processingThread )+    {+#ifdef CLOSE_THREAD_HANDLE+        CLOSE_THREAD_HANDLE( stream->processingThread ); /* Delete thread. */+#endif+        stream->processingThread = NULL;+    }+#endif++    return result;+}+++/***********************************************************************************/+static PaError StopStream( PaStream *s )+{+    PaError result = paNoError;+    PaWinDsStream *stream = (PaWinDsStream*)s;+    HRESULT          hr;+    int timeoutMsec;++    if( stream->streamRepresentation.streamCallback )+    {+        stream->stopProcessing = 1;++        /* Set timeout at 4 times maximum time we might wait. */+        timeoutMsec = (int) (4 * MSECS_PER_SECOND * (stream->hostBufferSizeFrames / stream->streamRepresentation.streamInfo.sampleRate));++        WaitForSingleObject( stream->processingCompleted, timeoutMsec );+    }++#ifdef PA_WIN_DS_USE_WMME_TIMER+    if( stream->timerID != 0 )+    {+        timeKillEvent(stream->timerID);  /* Stop callback timer. */+        stream->timerID = 0;+    }+#else+    if( stream->processingThread )+    {+		if( WaitForSingleObject( stream->processingThreadCompleted, 30*100 ) == WAIT_TIMEOUT )+			return paUnanticipatedHostError;++#ifdef CLOSE_THREAD_HANDLE+        CloseHandle( stream->processingThread ); /* Delete thread. */+        stream->processingThread = NULL;+#endif++    }+#endif++    if( stream->systemTimerResolutionPeriodMs > 0 ){+        timeEndPeriod( stream->systemTimerResolutionPeriodMs );+        stream->systemTimerResolutionPeriodMs = 0;+    }  ++    if( stream->bufferProcessor.outputChannelCount > 0 )+    {+        // Stop the buffer playback+        if( stream->pDirectSoundOutputBuffer != NULL )+        {+            stream->outputIsRunning = FALSE;+            // FIXME: what happens if IDirectSoundBuffer_Stop returns an error?+            hr = IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );++            if( stream->pDirectSoundPrimaryBuffer )+                IDirectSoundBuffer_Stop( stream->pDirectSoundPrimaryBuffer ); /* FIXME we never started the primary buffer so I'm not sure we need to stop it */+        }+    }++    if( stream->bufferProcessor.inputChannelCount > 0 )+    {+        // Stop the buffer capture+        if( stream->pDirectSoundInputBuffer != NULL )+        {+            // FIXME: what happens if IDirectSoundCaptureBuffer_Stop returns an error?+            hr = IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );+        }+    }++    stream->isStarted = 0;++    return result;+}+++/***********************************************************************************/+static PaError AbortStream( PaStream *s )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    stream->abortProcessing = 1;+    return StopStream( s );+}+++/***********************************************************************************/+static PaError IsStreamStopped( PaStream *s )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    return !stream->isStarted;+}+++/***********************************************************************************/+static PaError IsStreamActive( PaStream *s )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    return stream->isActive;+}++/***********************************************************************************/+static PaTime GetStreamTime( PaStream *s )+{+    /* suppress unused variable warnings */+    (void) s;++    return PaUtil_GetTime();+}+++/***********************************************************************************/+static double GetStreamCpuLoad( PaStream* s )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );+}+++/***********************************************************************************+    As separate stream interfaces are used for blocking and callback+    streams, the following functions can be guaranteed to only be called+    for blocking streams.+*/++static PaError ReadStream( PaStream* s,+                           void *buffer,+                           unsigned long frames )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    /* suppress unused variable warnings */+    (void) buffer;+    (void) frames;+    (void) stream;++    /* IMPLEMENT ME, see portaudio.h for required behavior*/++    return paNoError;+}+++/***********************************************************************************/+static PaError WriteStream( PaStream* s,+                            const void *buffer,+                            unsigned long frames )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    /* suppress unused variable warnings */+    (void) buffer;+    (void) frames;+    (void) stream;++    /* IMPLEMENT ME, see portaudio.h for required behavior*/++    return paNoError;+}+++/***********************************************************************************/+static signed long GetStreamReadAvailable( PaStream* s )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    /* suppress unused variable warnings */+    (void) stream;++    /* IMPLEMENT ME, see portaudio.h for required behavior*/++    return 0;+}+++/***********************************************************************************/+static signed long GetStreamWriteAvailable( PaStream* s )+{+    PaWinDsStream *stream = (PaWinDsStream*)s;++    /* suppress unused variable warnings */+    (void) stream;+    +    /* IMPLEMENT ME, see portaudio.h for required behavior*/++    return 0;+}+
+ portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c view
@@ -0,0 +1,224 @@+/*+ * Interface for dynamically loading directsound and providing a dummy+ * implementation if it isn't present.+ *+ * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)+ *+ * For PortAudio Portable Real-Time Audio Library+ * For more information see: http://www.portaudio.com+ * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/**+ @file+ @ingroup hostapi_src+*/++#include "pa_win_ds_dynlink.h"+#include "pa_debugprint.h"++PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints = { 0, 0, 0, 0, 0, 0, 0 };+++static HRESULT WINAPI DummyDllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)+{+    (void)rclsid; /* unused parameter */+    (void)riid; /* unused parameter */+    (void)ppv; /* unused parameter */+    return CLASS_E_CLASSNOTAVAILABLE;+}++static HRESULT WINAPI DummyDirectSoundCreate(LPGUID lpcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter)+{+    (void)lpcGuidDevice; /* unused parameter */+    (void)ppDS; /* unused parameter */+    (void)pUnkOuter; /* unused parameter */+    return E_NOTIMPL;+}++static HRESULT WINAPI DummyDirectSoundEnumerateW(LPDSENUMCALLBACKW lpDSEnumCallback, LPVOID lpContext)+{+    (void)lpDSEnumCallback; /* unused parameter */+    (void)lpContext; /* unused parameter */+    return E_NOTIMPL;+}++static HRESULT WINAPI DummyDirectSoundEnumerateA(LPDSENUMCALLBACKA lpDSEnumCallback, LPVOID lpContext)+{+    (void)lpDSEnumCallback; /* unused parameter */+    (void)lpContext; /* unused parameter */+    return E_NOTIMPL;+}++static HRESULT WINAPI DummyDirectSoundCaptureCreate(LPGUID lpcGUID, LPDIRECTSOUNDCAPTURE *lplpDSC, LPUNKNOWN pUnkOuter)+{+    (void)lpcGUID; /* unused parameter */+    (void)lplpDSC; /* unused parameter */+    (void)pUnkOuter; /* unused parameter */+    return E_NOTIMPL;+}++static HRESULT WINAPI DummyDirectSoundCaptureEnumerateW(LPDSENUMCALLBACKW lpDSCEnumCallback, LPVOID lpContext)+{+    (void)lpDSCEnumCallback; /* unused parameter */+    (void)lpContext; /* unused parameter */+    return E_NOTIMPL;+}++static HRESULT WINAPI DummyDirectSoundCaptureEnumerateA(LPDSENUMCALLBACKA lpDSCEnumCallback, LPVOID lpContext)+{+    (void)lpDSCEnumCallback; /* unused parameter */+    (void)lpContext; /* unused parameter */+    return E_NOTIMPL;+}++#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+static HRESULT WINAPI DummyDirectSoundFullDuplexCreate8(+         LPCGUID pcGuidCaptureDevice,+         LPCGUID pcGuidRenderDevice,+         LPCDSCBUFFERDESC pcDSCBufferDesc,+         LPCDSBUFFERDESC pcDSBufferDesc,+         HWND hWnd,+         DWORD dwLevel,+         LPDIRECTSOUNDFULLDUPLEX * ppDSFD,+         LPDIRECTSOUNDCAPTUREBUFFER8 * ppDSCBuffer8,+         LPDIRECTSOUNDBUFFER8 * ppDSBuffer8,+         LPUNKNOWN pUnkOuter)+{+    (void)pcGuidCaptureDevice; /* unused parameter */+    (void)pcGuidRenderDevice; /* unused parameter */+    (void)pcDSCBufferDesc; /* unused parameter */+    (void)pcDSBufferDesc; /* unused parameter */+    (void)hWnd; /* unused parameter */+    (void)dwLevel; /* unused parameter */+    (void)ppDSFD; /* unused parameter */+    (void)ppDSCBuffer8; /* unused parameter */+    (void)ppDSBuffer8; /* unused parameter */+    (void)pUnkOuter; /* unused parameter */++    return E_NOTIMPL;+}+#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */++void PaWinDs_InitializeDSoundEntryPoints(void)+{+    paWinDsDSoundEntryPoints.hInstance_ = LoadLibraryA("dsound.dll");+    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )+    {+        paWinDsDSoundEntryPoints.DllGetClassObject =+                (HRESULT (WINAPI *)(REFCLSID, REFIID , LPVOID *))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DllGetClassObject" );+        if( paWinDsDSoundEntryPoints.DllGetClassObject == NULL )+            paWinDsDSoundEntryPoints.DllGetClassObject = DummyDllGetClassObject;++        paWinDsDSoundEntryPoints.DirectSoundCreate =+                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCreate" );+        if( paWinDsDSoundEntryPoints.DirectSoundCreate == NULL )+            paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;++        paWinDsDSoundEntryPoints.DirectSoundEnumerateW =+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateW" );+        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateW == NULL )+            paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;++        paWinDsDSoundEntryPoints.DirectSoundEnumerateA =+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateA" );+        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateA == NULL )+            paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;++        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate =+                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureCreate" );+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureCreate == NULL )+            paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;++        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW =+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateW" );+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW == NULL )+            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;++        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA =+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateA" );+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA == NULL )+            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;++#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+        paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 =+                (HRESULT (WINAPI *)(LPCGUID, LPCGUID, LPCDSCBUFFERDESC, LPCDSBUFFERDESC,+                                    HWND, DWORD, LPDIRECTSOUNDFULLDUPLEX *, LPDIRECTSOUNDCAPTUREBUFFER8 *, +                                    LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN))+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundFullDuplexCreate" );+        if( paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 == NULL )+            paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;+#endif+    }+    else+    {+        DWORD errorCode = GetLastError(); // 126 (0x7E) == ERROR_MOD_NOT_FOUND+        PA_DEBUG(("Couldn't load dsound.dll error code: %d \n",errorCode));++        /* initialize with dummy entry points to make live easy when ds isn't present */+        paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;+#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE+        paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;+#endif+    }+}+++void PaWinDs_TerminateDSoundEntryPoints(void)+{+    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )+    {+        /* ensure that we crash reliably if the entry points arent initialised */+        paWinDsDSoundEntryPoints.DirectSoundCreate = 0;+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = 0;+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = 0;+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = 0;+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = 0;+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = 0;++        FreeLibrary( paWinDsDSoundEntryPoints.hInstance_ );+        paWinDsDSoundEntryPoints.hInstance_ = NULL;+    }+}
+ portaudio/src/hostapi/wasapi/pa_win_wasapi.c view
@@ -0,0 +1,5181 @@+/*
+ * Portable Audio I/O Library WASAPI implementation
+ * Copyright (c) 2006-2010 David Viens, Dmitry Kostjuchenko
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup hostapi_src
+ @brief WASAPI implementation of support for a host API.
+ @note pa_wasapi currently requires minimum VC 2005, and the latest Vista SDK
+*/
+
+#define WIN32_LEAN_AND_MEAN // exclude rare headers
+#include <windows.h>
+#include <stdio.h>
+#include <process.h>
+#include <assert.h>
+#include <mmsystem.h>
+#include <mmreg.h>  // must be before other Wasapi headers
+#if defined(_MSC_VER) && (_MSC_VER >= 1400)
+	#include <Avrt.h>
+	#define COBJMACROS
+	#include <Audioclient.h>
+	#include <endpointvolume.h>
+	#define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
+	#include <mmdeviceapi.h>
+	#include <functiondiscoverykeys.h>
+    #include <devicetopology.h>	// Used to get IKsJackDescription interface
+	#undef INITGUID
+#endif
+#ifndef __MWERKS__
+#include <malloc.h>
+#include <memory.h>
+#endif /* __MWERKS__ */
+
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_win_wasapi.h"
+#include "pa_debugprint.h"
+#include "pa_ringbuffer.h"
+
+#include "pa_win_coinitialize.h"
+
+#ifndef NTDDI_VERSION
+ 
+    #undef WINVER
+    #undef _WIN32_WINNT
+    #define WINVER       0x0600 // VISTA
+	#define _WIN32_WINNT WINVER
+
+	#ifndef _AVRT_ //<< fix MinGW dummy compile by defining missing type: AVRT_PRIORITY
+        typedef enum _AVRT_PRIORITY
+        {
+            AVRT_PRIORITY_LOW = -1,
+            AVRT_PRIORITY_NORMAL,
+            AVRT_PRIORITY_HIGH,
+            AVRT_PRIORITY_CRITICAL
+        } AVRT_PRIORITY, *PAVRT_PRIORITY;
+	#endif
+
+	#include <basetyps.h> // << for IID/CLSID
+    #include <rpcsal.h>
+    #include <sal.h>
+
+	#ifndef __LPCGUID_DEFINED__
+		#define __LPCGUID_DEFINED__
+		typedef const GUID *LPCGUID;
+	#endif
+
+    #ifndef PROPERTYKEY_DEFINED
+        #define PROPERTYKEY_DEFINED
+        typedef struct _tagpropertykey
+        {
+            GUID fmtid;
+            DWORD pid;
+        } 	PROPERTYKEY;
+    #endif
+
+    #ifdef __midl_proxy
+        #define __MIDL_CONST
+    #else
+        #define __MIDL_CONST const
+    #endif
+
+    #ifdef WIN64
+        #include <wtypes.h>
+        typedef LONG NTSTATUS;
+        #define FASTCALL
+        #include <oleidl.h>
+        #include <objidl.h>
+     #else
+        typedef struct _BYTE_BLOB
+        {
+            unsigned long clSize;
+            unsigned char abData[ 1 ];
+        } 	BYTE_BLOB;
+        typedef /* [unique] */  __RPC_unique_pointer BYTE_BLOB *UP_BYTE_BLOB;
+        typedef LONGLONG REFERENCE_TIME;
+        #define NONAMELESSUNION
+    #endif
+    
+    #ifndef WAVE_FORMAT_IEEE_FLOAT
+        #define WAVE_FORMAT_IEEE_FLOAT 0x0003 // 32-bit floating-point
+    #endif    
+    
+    #ifndef __MINGW_EXTENSION
+        #if defined(__GNUC__) || defined(__GNUG__)
+            #define __MINGW_EXTENSION __extension__
+        #else
+            #define __MINGW_EXTENSION
+        #endif
+    #endif 
+
+    #include <sdkddkver.h>
+    #include <propkeydef.h>
+    #define COBJMACROS
+    #define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
+    #include <audioclient.h>
+    #include <mmdeviceapi.h>
+    #include <endpointvolume.h>
+    #include <functiondiscoverykeys.h>
+	#include <devicetopology.h>	// Used to get IKsJackDescription interface
+    #undef INITGUID
+
+#endif // NTDDI_VERSION
+
+#ifndef GUID_SECT
+    #define GUID_SECT
+#endif
+
+#define __DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#define __DEFINE_IID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const IID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#define __DEFINE_CLSID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const CLSID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
+#define PA_DEFINE_CLSID(className, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
+    __DEFINE_CLSID(pa_CLSID_##className, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
+#define PA_DEFINE_IID(interfaceName, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
+    __DEFINE_IID(pa_IID_##interfaceName, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
+
+// "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"
+PA_DEFINE_IID(IAudioClient,         1cb9ad4c, dbfa, 4c32, b1, 78, c2, f5, 68, a7, 03, b2);
+// "1BE09788-6894-4089-8586-9A2A6C265AC5"
+PA_DEFINE_IID(IMMEndpoint,          1be09788, 6894, 4089, 85, 86, 9a, 2a, 6c, 26, 5a, c5);
+// "A95664D2-9614-4F35-A746-DE8DB63617E6"
+PA_DEFINE_IID(IMMDeviceEnumerator,  a95664d2, 9614, 4f35, a7, 46, de, 8d, b6, 36, 17, e6);
+// "BCDE0395-E52F-467C-8E3D-C4579291692E"
+PA_DEFINE_CLSID(IMMDeviceEnumerator,bcde0395, e52f, 467c, 8e, 3d, c4, 57, 92, 91, 69, 2e);
+// "F294ACFC-3146-4483-A7BF-ADDCA7C260E2"
+PA_DEFINE_IID(IAudioRenderClient,   f294acfc, 3146, 4483, a7, bf, ad, dc, a7, c2, 60, e2);
+// "C8ADBD64-E71E-48a0-A4DE-185C395CD317"
+PA_DEFINE_IID(IAudioCaptureClient,  c8adbd64, e71e, 48a0, a4, de, 18, 5c, 39, 5c, d3, 17);
+// *2A07407E-6497-4A18-9787-32F79BD0D98F*  Or this??
+PA_DEFINE_IID(IDeviceTopology,      2A07407E, 6497, 4A18, 97, 87, 32, f7, 9b, d0, d9, 8f);
+// *AE2DE0E4-5BCA-4F2D-AA46-5D13F8FDB3A9*
+PA_DEFINE_IID(IPart,                AE2DE0E4, 5BCA, 4F2D, aa, 46, 5d, 13, f8, fd, b3, a9);
+// *4509F757-2D46-4637-8E62-CE7DB944F57B*
+PA_DEFINE_IID(IKsJackDescription,   4509F757, 2D46, 4637, 8e, 62, ce, 7d, b9, 44, f5, 7b);
+// Media formats:
+__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_PCM,        0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
+__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_ADPCM,      0x00000002, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
+__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
+
+/* use CreateThread for CYGWIN/Windows Mobile, _beginthreadex for all others */
+#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
+	#define CREATE_THREAD(PROC) (HANDLE)_beginthreadex( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
+	#define PA_THREAD_FUNC static unsigned WINAPI
+	#define PA_THREAD_ID unsigned
+#else
+	#define CREATE_THREAD(PROC) CreateThread( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
+	#define PA_THREAD_FUNC static DWORD WINAPI
+	#define PA_THREAD_ID DWORD
+#endif
+
+// Thread function forward decl.
+PA_THREAD_FUNC ProcThreadEvent(void *param);
+PA_THREAD_FUNC ProcThreadPoll(void *param);
+
+// Availabe from Windows 7
+#ifndef AUDCLNT_E_BUFFER_ERROR
+	#define AUDCLNT_E_BUFFER_ERROR AUDCLNT_ERR(0x018)
+#endif
+#ifndef AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
+	#define AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED AUDCLNT_ERR(0x019)
+#endif
+#ifndef AUDCLNT_E_INVALID_DEVICE_PERIOD
+	#define AUDCLNT_E_INVALID_DEVICE_PERIOD AUDCLNT_ERR(0x020)
+#endif
+
+#define MAX_STR_LEN 512
+
+enum { S_INPUT = 0, S_OUTPUT = 1, S_COUNT = 2, S_FULLDUPLEX = 0 };
+
+// Number of packets which compose single contignous buffer. With trial and error it was calculated
+// that WASAPI Input sub-system uses 6 packets per whole buffer. Please provide more information
+// or corrections if available.
+enum { WASAPI_PACKETS_PER_INPUT_BUFFER = 6 };
+
+#define STATIC_ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
+
+#define PRINT(x) PA_DEBUG(x);
+
+#define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \
+    PaUtil_SetLastHostErrorInfo( paWASAPI, errorCode, errorText )
+
+#define PA_WASAPI__IS_FULLDUPLEX(STREAM) ((STREAM)->in.clientProc && (STREAM)->out.clientProc)
+
+#ifndef IF_FAILED_JUMP
+#define IF_FAILED_JUMP(hr, label) if(FAILED(hr)) goto label;
+#endif
+
+#ifndef IF_FAILED_INTERNAL_ERROR_JUMP
+#define IF_FAILED_INTERNAL_ERROR_JUMP(hr, error, label) if(FAILED(hr)) { error = paInternalError; goto label; }
+#endif
+
+#define SAFE_CLOSE(h) if ((h) != NULL) { CloseHandle((h)); (h) = NULL; }
+#define SAFE_RELEASE(punk) if ((punk) != NULL) { (punk)->lpVtbl->Release((punk)); (punk) = NULL; }
+
+// Mixer function
+typedef void (*MixMonoToStereoF) (void *__to, void *__from, UINT32 count);
+
+// AVRT is the new "multimedia schedulling stuff"
+typedef BOOL   (WINAPI *FAvRtCreateThreadOrderingGroup)  (PHANDLE,PLARGE_INTEGER,GUID*,PLARGE_INTEGER);
+typedef BOOL   (WINAPI *FAvRtDeleteThreadOrderingGroup)  (HANDLE);
+typedef BOOL   (WINAPI *FAvRtWaitOnThreadOrderingGroup)  (HANDLE);
+typedef HANDLE (WINAPI *FAvSetMmThreadCharacteristics)   (LPCSTR,LPDWORD);
+typedef BOOL   (WINAPI *FAvRevertMmThreadCharacteristics)(HANDLE);
+typedef BOOL   (WINAPI *FAvSetMmThreadPriority)          (HANDLE,AVRT_PRIORITY);
+
+static HMODULE hDInputDLL = 0;
+FAvRtCreateThreadOrderingGroup   pAvRtCreateThreadOrderingGroup = NULL;
+FAvRtDeleteThreadOrderingGroup   pAvRtDeleteThreadOrderingGroup = NULL;
+FAvRtWaitOnThreadOrderingGroup   pAvRtWaitOnThreadOrderingGroup = NULL;
+FAvSetMmThreadCharacteristics    pAvSetMmThreadCharacteristics = NULL;
+FAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
+FAvSetMmThreadPriority           pAvSetMmThreadPriority = NULL;
+
+#define _GetProc(fun, type, name)  {                                                        \
+                                        fun = (type) GetProcAddress(hDInputDLL,name);       \
+                                        if (fun == NULL) {                                  \
+                                            PRINT(("GetProcAddr failed for %s" ,name));     \
+                                            return FALSE;                                   \
+                                        }                                                   \
+                                    }                                                       \
+
+// ------------------------------------------------------------------------------------------
+/* prototypes for functions declared in this file */
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+// dummy entry point for other compilers and sdks
+// currently built using RC1 SDK (5600)
+//#if _MSC_VER < 1400
+//PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+//{
+    //return paNoError;
+//}
+//#else
+
+// ------------------------------------------------------------------------------------------
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+// ------------------------------------------------------------------------------------------
+/*
+ These are fields that can be gathered from IDevice and IAudioDevice PRIOR to Initialize, and
+ done in first pass i assume that neither of these will cause the Driver to "load", but again,
+ who knows how they implement their stuff
+ */
+typedef struct PaWasapiDeviceInfo
+{
+    // Device
+    IMMDevice *device;
+
+	// from GetId
+    WCHAR szDeviceID[MAX_STR_LEN];
+
+	// from GetState
+    DWORD state;
+
+    // Fields filled from IMMEndpoint'sGetDataFlow
+    EDataFlow flow;
+
+    // Fields filled from IAudioDevice (_prior_ to Initialize)
+    // from GetDevicePeriod(
+    REFERENCE_TIME DefaultDevicePeriod;
+    REFERENCE_TIME MinimumDevicePeriod;
+
+    // from GetMixFormat
+    // WAVEFORMATEX *MixFormat;//needs to be CoTaskMemFree'd after use!
+
+	// Default format (setup through Control Panel by user)
+	WAVEFORMATEXTENSIBLE DefaultFormat;
+
+	// Formfactor
+	EndpointFormFactor formFactor;
+}
+PaWasapiDeviceInfo;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiHostApiRepresentation - host api datastructure specific to this implementation */
+typedef struct
+{
+    PaUtilHostApiRepresentation inheritedHostApiRep;
+    PaUtilStreamInterface       callbackStreamInterface;
+    PaUtilStreamInterface       blockingStreamInterface;
+
+    PaUtilAllocationGroup      *allocations;
+
+    /* implementation specific data goes here */
+
+    PaWinUtilComInitializationResult comInitializationResult;
+
+    //in case we later need the synch
+    IMMDeviceEnumerator *enumerator;
+
+    //this is the REAL number of devices, whether they are usefull to PA or not!
+    UINT32 deviceCount;
+
+    WCHAR defaultRenderer [MAX_STR_LEN];
+    WCHAR defaultCapturer [MAX_STR_LEN];
+
+    PaWasapiDeviceInfo *devInfo;
+
+	// Is true when WOW64 Vista/7 Workaround is needed
+	BOOL useWOW64Workaround;
+}
+PaWasapiHostApiRepresentation;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiAudioClientParams - audio client parameters */
+typedef struct PaWasapiAudioClientParams
+{
+	PaWasapiDeviceInfo *device_info;
+	PaStreamParameters  stream_params;
+	PaWasapiStreamInfo  wasapi_params;
+	UINT32              frames_per_buffer;
+	double              sample_rate;
+	BOOL                blocking;
+	BOOL                full_duplex;
+	BOOL                wow64_workaround;
+}
+PaWasapiAudioClientParams;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiStream - a stream data structure specifically for this implementation */
+typedef struct PaWasapiSubStream
+{
+    IAudioClient        *clientParent;
+	IStream				*clientStream;
+	IAudioClient		*clientProc;
+
+    WAVEFORMATEXTENSIBLE wavex;
+    UINT32               bufferSize;
+    REFERENCE_TIME       deviceLatency;
+    REFERENCE_TIME       period;
+	double				 latencySeconds;
+    UINT32				 framesPerHostCallback;
+	AUDCLNT_SHAREMODE    shareMode;
+	UINT32               streamFlags; // AUDCLNT_STREAMFLAGS_EVENTCALLBACK, ...
+	UINT32               flags;
+	PaWasapiAudioClientParams params; //!< parameters
+
+	// Buffers
+	UINT32               buffers;			//!< number of buffers used (from host side)
+	UINT32               framesPerBuffer;	//!< number of frames per 1 buffer
+	BOOL                 userBufferAndHostMatch;
+
+	// Used for Mono >> Stereo workaround, if driver does not support it
+	// (in Exclusive mode WASAPI usually refuses to operate with Mono (1-ch)
+	void                *monoBuffer;	 //!< pointer to buffer
+	UINT32               monoBufferSize; //!< buffer size in bytes
+	MixMonoToStereoF     monoMixer;		 //!< pointer to mixer function
+
+	PaUtilRingBuffer    *tailBuffer;       //!< buffer with trailing sample for blocking mode operations (only for Input)
+	void                *tailBufferMemory; //!< tail buffer memory region
+}
+PaWasapiSubStream;
+
+// ------------------------------------------------------------------------------------------
+/* PaWasapiHostProcessor - redirects processing data */
+typedef struct PaWasapiHostProcessor
+{
+    PaWasapiHostProcessorCallback processor;
+    void *userData;
+}
+PaWasapiHostProcessor;
+
+// ------------------------------------------------------------------------------------------
+typedef struct PaWasapiStream
+{
+	/* IMPLEMENT ME: rename this */
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer      cpuLoadMeasurer;
+    PaUtilBufferProcessor      bufferProcessor;
+
+    // input
+	PaWasapiSubStream          in;
+    IAudioCaptureClient       *captureClientParent;
+	IStream                   *captureClientStream;
+	IAudioCaptureClient       *captureClient;
+    IAudioEndpointVolume      *inVol;
+
+	// output
+	PaWasapiSubStream          out;
+    IAudioRenderClient        *renderClientParent;
+	IStream                   *renderClientStream;
+	IAudioRenderClient        *renderClient;
+	IAudioEndpointVolume      *outVol;
+
+	// event handles for event-driven processing mode
+	HANDLE event[S_COUNT];
+
+	// buffer mode
+	PaUtilHostBufferSizeMode bufferMode;
+
+	// must be volatile to avoid race condition on user query while
+	// thread is being started
+    volatile BOOL running;
+
+    PA_THREAD_ID dwThreadId;
+    HANDLE hThread;
+	HANDLE hCloseRequest;
+	HANDLE hThreadStart;        //!< signalled by thread on start
+	HANDLE hThreadExit;         //!< signalled by thread on exit
+	HANDLE hBlockingOpStreamRD;
+	HANDLE hBlockingOpStreamWR;
+
+    // Host callback Output overrider
+	PaWasapiHostProcessor hostProcessOverrideOutput;
+
+    // Host callback Input overrider
+	PaWasapiHostProcessor hostProcessOverrideInput;
+
+	// Defines blocking/callback interface used
+	BOOL bBlocking;
+
+	// Av Task (MM thread management)
+	HANDLE hAvTask;
+
+	// Thread priority level
+	PaWasapiThreadPriority nThreadPriority;
+}
+PaWasapiStream;
+
+// Local stream methods
+void _StreamOnStop(PaWasapiStream *stream);
+void _StreamFinish(PaWasapiStream *stream);
+void _StreamCleanup(PaWasapiStream *stream);
+HRESULT _PollGetOutputFramesAvailable(PaWasapiStream *stream, UINT32 *available);
+HRESULT _PollGetInputFramesAvailable(PaWasapiStream *stream, UINT32 *available);
+void *PaWasapi_ReallocateMemory(void *ptr, size_t size);
+void PaWasapi_FreeMemory(void *ptr);
+
+// Local statics
+
+// ------------------------------------------------------------------------------------------
+#define LogHostError(HRES) __LogHostError(HRES, __FUNCTION__, __FILE__, __LINE__)
+static HRESULT __LogHostError(HRESULT res, const char *func, const char *file, int line)
+{
+    const char *text = NULL;
+    switch (res)
+	{
+	case S_OK: return res;
+	case E_POINTER                              :text ="E_POINTER"; break;
+	case E_INVALIDARG                           :text ="E_INVALIDARG"; break;
+
+	case AUDCLNT_E_NOT_INITIALIZED              :text ="AUDCLNT_E_NOT_INITIALIZED"; break;
+	case AUDCLNT_E_ALREADY_INITIALIZED          :text ="AUDCLNT_E_ALREADY_INITIALIZED"; break;
+	case AUDCLNT_E_WRONG_ENDPOINT_TYPE          :text ="AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
+	case AUDCLNT_E_DEVICE_INVALIDATED           :text ="AUDCLNT_E_DEVICE_INVALIDATED"; break;
+	case AUDCLNT_E_NOT_STOPPED                  :text ="AUDCLNT_E_NOT_STOPPED"; break;
+	case AUDCLNT_E_BUFFER_TOO_LARGE             :text ="AUDCLNT_E_BUFFER_TOO_LARGE"; break;
+	case AUDCLNT_E_OUT_OF_ORDER                 :text ="AUDCLNT_E_OUT_OF_ORDER"; break;
+	case AUDCLNT_E_UNSUPPORTED_FORMAT           :text ="AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
+	case AUDCLNT_E_INVALID_SIZE                 :text ="AUDCLNT_E_INVALID_SIZE"; break;
+	case AUDCLNT_E_DEVICE_IN_USE                :text ="AUDCLNT_E_DEVICE_IN_USE"; break;
+	case AUDCLNT_E_BUFFER_OPERATION_PENDING     :text ="AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
+	case AUDCLNT_E_THREAD_NOT_REGISTERED        :text ="AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
+	case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED   :text ="AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
+	case AUDCLNT_E_ENDPOINT_CREATE_FAILED       :text ="AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
+	case AUDCLNT_E_SERVICE_NOT_RUNNING          :text ="AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
+	case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED     :text ="AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
+	case AUDCLNT_E_EXCLUSIVE_MODE_ONLY          :text ="AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
+	case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL :text ="AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
+	case AUDCLNT_E_EVENTHANDLE_NOT_SET          :text ="AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
+	case AUDCLNT_E_INCORRECT_BUFFER_SIZE        :text ="AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
+	case AUDCLNT_E_BUFFER_SIZE_ERROR            :text ="AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
+	case AUDCLNT_E_CPUUSAGE_EXCEEDED            :text ="AUDCLNT_E_CPUUSAGE_EXCEEDED"; break;
+	case AUDCLNT_E_BUFFER_ERROR					:text ="AUDCLNT_E_BUFFER_ERROR"; break;
+	case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED		:text ="AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED"; break;
+	case AUDCLNT_E_INVALID_DEVICE_PERIOD		:text ="AUDCLNT_E_INVALID_DEVICE_PERIOD"; break;
+
+	case AUDCLNT_S_BUFFER_EMPTY                 :text ="AUDCLNT_S_BUFFER_EMPTY"; break;
+	case AUDCLNT_S_THREAD_ALREADY_REGISTERED    :text ="AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
+	case AUDCLNT_S_POSITION_STALLED				:text ="AUDCLNT_S_POSITION_STALLED"; break;
+
+	// other windows common errors:
+	case CO_E_NOTINITIALIZED                    :text ="CO_E_NOTINITIALIZED: you must call CoInitialize() before Pa_OpenStream()"; break;
+
+	default:
+		text = "UNKNOWN ERROR";
+    }
+	PRINT(("WASAPI ERROR HRESULT: 0x%X : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", res, text, func, file, line));
+	PA_SKELETON_SET_LAST_HOST_ERROR(res, text);
+	return res;
+}
+
+// ------------------------------------------------------------------------------------------
+#define LogPaError(PAERR) __LogPaError(PAERR, __FUNCTION__, __FILE__, __LINE__)
+static PaError __LogPaError(PaError err, const char *func, const char *file, int line)
+{
+	if (err == paNoError)
+		return err;
+	PRINT(("WASAPI ERROR PAERROR: %i : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", err, Pa_GetErrorText(err), func, file, line));
+	return err;
+}
+
+// ------------------------------------------------------------------------------------------
+/*! \class ThreadSleepScheduler
+           Allows to emulate thread sleep of less than 1 millisecond under Windows. Scheduler
+		   calculates number of times the thread must run untill next sleep of 1 millisecond.
+		   It does not make thread sleeping for real number of microseconds but rather controls
+		   how many of imaginary microseconds the thread task can allow thread to sleep.
+*/
+typedef struct ThreadIdleScheduler
+{
+	UINT32 m_idle_microseconds; //!< number of microseconds to sleep
+	UINT32 m_next_sleep;        //!< next sleep round
+	UINT32 m_i;					//!< current round iterator position
+	UINT32 m_resolution;		//!< resolution in number of milliseconds
+}
+ThreadIdleScheduler;
+//! Setup scheduler.
+static void ThreadIdleScheduler_Setup(ThreadIdleScheduler *sched, UINT32 resolution, UINT32 microseconds)
+{
+	assert(microseconds != 0);
+	assert(resolution != 0);
+	assert((resolution * 1000) >= microseconds);
+
+	memset(sched, 0, sizeof(*sched));
+
+	sched->m_idle_microseconds = microseconds;
+	sched->m_resolution        = resolution;
+	sched->m_next_sleep        = (resolution * 1000) / microseconds;
+}
+//! Iterate and check if can sleep.
+static UINT32 ThreadIdleScheduler_NextSleep(ThreadIdleScheduler *sched)
+{
+	// advance and check if thread can sleep
+	if (++ sched->m_i == sched->m_next_sleep)
+	{
+		sched->m_i = 0;
+		return sched->m_resolution;
+	}
+	return 0;
+}
+
+// ------------------------------------------------------------------------------------------
+/*static double nano100ToMillis(REFERENCE_TIME ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return ((double)ref)*0.0001;
+}*/
+
+// ------------------------------------------------------------------------------------------
+static double nano100ToSeconds(REFERENCE_TIME ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return ((double)ref)*0.0000001;
+}
+
+// ------------------------------------------------------------------------------------------
+/*static REFERENCE_TIME MillisTonano100(double ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return (REFERENCE_TIME)(ref/0.0001);
+}*/
+
+// ------------------------------------------------------------------------------------------
+static REFERENCE_TIME SecondsTonano100(double ref)
+{
+    //  1 nano = 0.000000001 seconds
+    //100 nano = 0.0000001   seconds
+    //100 nano = 0.0001   milliseconds
+    return (REFERENCE_TIME)(ref/0.0000001);
+}
+
+// ------------------------------------------------------------------------------------------
+// Makes Hns period from frames and sample rate
+static REFERENCE_TIME MakeHnsPeriod(UINT32 nFrames, DWORD nSamplesPerSec)
+{
+	return (REFERENCE_TIME)((10000.0 * 1000 / nSamplesPerSec * nFrames) + 0.5);
+}
+
+// ------------------------------------------------------------------------------------------
+// Converts PaSampleFormat to bits per sample value
+static WORD PaSampleFormatToBitsPerSample(PaSampleFormat format_id)
+{
+	switch (format_id & ~paNonInterleaved)
+	{
+		case paFloat32:
+		case paInt32: return 32;
+		case paInt24: return 24;
+		case paInt16: return 16;
+		case paInt8:
+		case paUInt8: return 8;
+	}
+	return 0;
+}
+
+// ------------------------------------------------------------------------------------------
+// Converts PaSampleFormat to bits per sample value
+/*static WORD PaSampleFormatToBytesPerSample(PaSampleFormat format_id)
+{
+	return PaSampleFormatToBitsPerSample(format_id) >> 3; // 'bits/8'
+}*/
+
+// ------------------------------------------------------------------------------------------
+// Converts Hns period into number of frames
+static UINT32 MakeFramesFromHns(REFERENCE_TIME hnsPeriod, UINT32 nSamplesPerSec)
+{
+    UINT32 nFrames = (UINT32)(	// frames =
+        1.0 * hnsPeriod *		// hns *
+        nSamplesPerSec /		// (frames / s) /
+        1000 /					// (ms / s) /
+        10000					// (hns / s) /
+        + 0.5					// rounding
+    );
+	return nFrames;
+}
+
+// Aligning function type
+typedef UINT32 (*ALIGN_FUNC) (UINT32 v, UINT32 align);
+
+// ------------------------------------------------------------------------------------------
+// Aligns 'v' backwards
+static UINT32 ALIGN_BWD(UINT32 v, UINT32 align)
+{
+	return ((v - (align ? v % align : 0)));
+}
+
+// ------------------------------------------------------------------------------------------
+// Aligns 'v' forward
+static UINT32 ALIGN_FWD(UINT32 v, UINT32 align)
+{
+	UINT32 remainder = (align ? (v % align) : 0);
+	if (remainder == 0)
+		return v;
+	return v + (align - remainder);
+}
+
+// ------------------------------------------------------------------------------------------
+// Get next value power of 2
+UINT32 ALIGN_NEXT_POW2(UINT32 v)
+{
+	UINT32 v2 = 1;
+	while (v > (v2 <<= 1)) { }
+	v = v2;
+	return v;
+}
+
+// ------------------------------------------------------------------------------------------
+// Aligns WASAPI buffer to 128 byte packet boundary. HD Audio will fail to play if buffer
+// is misaligned. This problem was solved in Windows 7 were AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
+// is thrown although we must align for Vista anyway.
+static UINT32 AlignFramesPerBuffer(UINT32 nFrames, UINT32 nSamplesPerSec, UINT32 nBlockAlign,
+								   ALIGN_FUNC pAlignFunc)
+{
+#define HDA_PACKET_SIZE (128)
+
+	long frame_bytes = nFrames * nBlockAlign;
+	long packets;
+
+	// align to packet size
+	frame_bytes  = pAlignFunc(frame_bytes, HDA_PACKET_SIZE); // use ALIGN_FWD if bigger but safer period is more desired
+
+	// atlest 1 frame must be available
+	if (frame_bytes < HDA_PACKET_SIZE)
+		frame_bytes = HDA_PACKET_SIZE;
+
+	nFrames      = frame_bytes / nBlockAlign;
+	packets      = frame_bytes / HDA_PACKET_SIZE;
+
+	frame_bytes = packets * HDA_PACKET_SIZE;
+	nFrames     = frame_bytes / nBlockAlign;
+
+	return nFrames;
+
+#undef HDA_PACKET_SIZE
+}
+
+// ------------------------------------------------------------------------------------------
+static UINT32 GetFramesSleepTime(UINT32 nFrames, UINT32 nSamplesPerSec)
+{
+	REFERENCE_TIME nDuration;
+	if (nSamplesPerSec == 0)
+		return 0;
+#define REFTIMES_PER_SEC  10000000
+#define REFTIMES_PER_MILLISEC  10000
+	// Calculate the actual duration of the allocated buffer.
+	nDuration = (REFERENCE_TIME)((double)REFTIMES_PER_SEC * nFrames / nSamplesPerSec);
+	return (UINT32)(nDuration/REFTIMES_PER_MILLISEC/2);
+}
+
+// ------------------------------------------------------------------------------------------
+static UINT32 GetFramesSleepTimeMicroseconds(UINT32 nFrames, UINT32 nSamplesPerSec)
+{
+	REFERENCE_TIME nDuration;
+	if (nSamplesPerSec == 0)
+		return 0;
+#define REFTIMES_PER_SEC  10000000
+#define REFTIMES_PER_MILLISEC  10000
+	// Calculate the actual duration of the allocated buffer.
+	nDuration = (REFERENCE_TIME)((double)REFTIMES_PER_SEC * nFrames / nSamplesPerSec);
+	return (UINT32)(nDuration/10/2);
+}
+
+// ------------------------------------------------------------------------------------------
+static BOOL SetupAVRT()
+{
+    hDInputDLL = LoadLibraryA("avrt.dll");
+    if (hDInputDLL == NULL)
+        return FALSE;
+
+    _GetProc(pAvRtCreateThreadOrderingGroup,  FAvRtCreateThreadOrderingGroup,  "AvRtCreateThreadOrderingGroup");
+    _GetProc(pAvRtDeleteThreadOrderingGroup,  FAvRtDeleteThreadOrderingGroup,  "AvRtDeleteThreadOrderingGroup");
+    _GetProc(pAvRtWaitOnThreadOrderingGroup,  FAvRtWaitOnThreadOrderingGroup,  "AvRtWaitOnThreadOrderingGroup");
+    _GetProc(pAvSetMmThreadCharacteristics,   FAvSetMmThreadCharacteristics,   "AvSetMmThreadCharacteristicsA");
+	_GetProc(pAvRevertMmThreadCharacteristics,FAvRevertMmThreadCharacteristics,"AvRevertMmThreadCharacteristics");
+    _GetProc(pAvSetMmThreadPriority,          FAvSetMmThreadPriority,          "AvSetMmThreadPriority");
+
+	return pAvRtCreateThreadOrderingGroup &&
+		pAvRtDeleteThreadOrderingGroup &&
+		pAvRtWaitOnThreadOrderingGroup &&
+		pAvSetMmThreadCharacteristics &&
+		pAvRevertMmThreadCharacteristics &&
+		pAvSetMmThreadPriority;
+}
+
+// ------------------------------------------------------------------------------------------
+static void CloseAVRT()
+{
+	if (hDInputDLL != NULL)
+		FreeLibrary(hDInputDLL);
+	hDInputDLL = NULL;
+}
+
+// ------------------------------------------------------------------------------------------
+static BOOL IsWow64()
+{
+	// http://msdn.microsoft.com/en-us/library/ms684139(VS.85).aspx
+
+	typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
+	LPFN_ISWOW64PROCESS fnIsWow64Process;
+
+    BOOL bIsWow64 = FALSE;
+
+    // IsWow64Process is not available on all supported versions of Windows.
+    // Use GetModuleHandle to get a handle to the DLL that contains the function
+    // and GetProcAddress to get a pointer to the function if available.
+
+    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
+        GetModuleHandleA("kernel32"), "IsWow64Process");
+
+    if (fnIsWow64Process == NULL)
+		return FALSE;
+
+    if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
+		return FALSE;
+
+    return bIsWow64;
+}
+
+// ------------------------------------------------------------------------------------------
+typedef enum EWindowsVersion
+{
+	WINDOWS_UNKNOWN			 = 0,
+	WINDOWS_VISTA_SERVER2008 = (1 << 0),
+	WINDOWS_7_SERVER2008R2	 = (1 << 1),
+	WINDOWS_FUTURE           = (1 << 2)
+}
+EWindowsVersion;
+// Defines Windows 7/Windows Server 2008 R2 and up (future versions)
+#define WINDOWS_7_SERVER2008R2_AND_UP (WINDOWS_7_SERVER2008R2|WINDOWS_FUTURE)
+// The function is limited to Vista/7 mostly as we need just to find out Vista/WOW64 combination
+// in order to use WASAPI WOW64 workarounds.
+static UINT32 GetWindowsVersion()
+{
+	static UINT32 version = WINDOWS_UNKNOWN;
+
+	if (version == WINDOWS_UNKNOWN)
+	{
+		DWORD dwVersion = 0;
+		DWORD dwMajorVersion = 0;
+		DWORD dwMinorVersion = 0;
+		DWORD dwBuild = 0;
+
+		typedef DWORD (WINAPI *LPFN_GETVERSION)(VOID);
+		LPFN_GETVERSION fnGetVersion;
+
+		fnGetVersion = (LPFN_GETVERSION) GetProcAddress(GetModuleHandleA("kernel32"), "GetVersion");
+		if (fnGetVersion == NULL)
+			return WINDOWS_UNKNOWN;
+
+		dwVersion = fnGetVersion();
+
+		// Get the Windows version
+		dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
+		dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
+
+		// Get the build number
+		if (dwVersion < 0x80000000)
+			dwBuild = (DWORD)(HIWORD(dwVersion));
+
+		switch (dwMajorVersion)
+		{
+		case 0:
+		case 1:
+		case 2:
+		case 3:
+		case 4:
+		case 5:
+			break; // skip lower
+		case 6:
+			switch (dwMinorVersion)
+			{
+			case 0:
+				version |= WINDOWS_VISTA_SERVER2008;
+				break;
+			case 1:
+				version |= WINDOWS_7_SERVER2008R2;
+				break;
+			default:
+				version |= WINDOWS_FUTURE;
+			}
+			break;
+		default:
+			version |= WINDOWS_FUTURE;
+		}
+	}
+
+	return version;
+}
+
+// ------------------------------------------------------------------------------------------
+static BOOL UseWOW64Workaround()
+{
+	// note: WOW64 bug is common to Windows Vista x64, thus we fall back to safe Poll-driven
+	//       method. Windows 7 x64 seems has WOW64 bug fixed.
+
+	return (IsWow64() && (GetWindowsVersion() & WINDOWS_VISTA_SERVER2008));
+}
+
+// ------------------------------------------------------------------------------------------
+typedef enum EMixerDir { MIX_DIR__1TO2, MIX_DIR__2TO1, MIX_DIR__2TO1_L } EMixerDir;
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(TYPE)\
+	TYPE * __restrict to   = __to;\
+	TYPE * __restrict from = __from;\
+	TYPE * __restrict end  = from + count;\
+	while (from != end)\
+	{\
+		*to ++ = *from;\
+		*to ++ = *from;\
+		++ from;\
+	}
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_FLT32(TYPE)\
+	TYPE * __restrict to   = (TYPE *)__to;\
+	TYPE * __restrict from = (TYPE *)__from;\
+	TYPE * __restrict end  = to + count;\
+	while (to != end)\
+	{\
+		*to ++ = (TYPE)((float)(from[0] + from[1]) * 0.5f);\
+		from += 2;\
+	}
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(TYPE)\
+	TYPE * __restrict to   = (TYPE *)__to;\
+	TYPE * __restrict from = (TYPE *)__from;\
+	TYPE * __restrict end  = to + count;\
+	while (to != end)\
+	{\
+		*to ++ = (TYPE)(((INT32)from[0] + (INT32)from[1]) >> 1);\
+		from += 2;\
+	}
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT64(TYPE)\
+	TYPE * __restrict to   = (TYPE *)__to;\
+	TYPE * __restrict from = (TYPE *)__from;\
+	TYPE * __restrict end  = to + count;\
+	while (to != end)\
+	{\
+		*to ++ = (TYPE)(((INT64)from[0] + (INT64)from[1]) >> 1);\
+		from += 2;\
+	}
+
+// ------------------------------------------------------------------------------------------
+#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(TYPE)\
+	TYPE * __restrict to   = (TYPE *)__to;\
+	TYPE * __restrict from = (TYPE *)__from;\
+	TYPE * __restrict end  = to + count;\
+	while (to != end)\
+	{\
+		*to ++ = from[0];\
+		from += 2;\
+	}
+
+// ------------------------------------------------------------------------------------------
+static void _MixMonoToStereo_1TO2_8(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(BYTE); }
+static void _MixMonoToStereo_1TO2_16(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(short); }
+static void _MixMonoToStereo_1TO2_24(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); /* !!! int24 data is contained in 32-bit containers*/ }
+static void _MixMonoToStereo_1TO2_32(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); }
+static void _MixMonoToStereo_1TO2_32f(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(float); }
+
+// ------------------------------------------------------------------------------------------
+static void _MixMonoToStereo_2TO1_8(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(BYTE); }
+static void _MixMonoToStereo_2TO1_16(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(short); }
+static void _MixMonoToStereo_2TO1_24(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(int); /* !!! int24 data is contained in 32-bit containers*/ }
+static void _MixMonoToStereo_2TO1_32(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT64(int); }
+static void _MixMonoToStereo_2TO1_32f(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_FLT32(float); }
+
+// ------------------------------------------------------------------------------------------
+static void _MixMonoToStereo_2TO1_8_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(BYTE); }
+static void _MixMonoToStereo_2TO1_16_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(short); }
+static void _MixMonoToStereo_2TO1_24_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(int); /* !!! int24 data is contained in 32-bit containers*/ }
+static void _MixMonoToStereo_2TO1_32_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(int); }
+static void _MixMonoToStereo_2TO1_32f_L(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(float); }
+
+// ------------------------------------------------------------------------------------------
+static MixMonoToStereoF _GetMonoToStereoMixer(PaSampleFormat format, EMixerDir dir)
+{
+	switch (dir)
+	{
+	case MIX_DIR__1TO2:
+		switch (format & ~paNonInterleaved)
+		{
+		case paUInt8:	return _MixMonoToStereo_1TO2_8;
+		case paInt16:	return _MixMonoToStereo_1TO2_16;
+		case paInt24:	return _MixMonoToStereo_1TO2_24;
+		case paInt32:	return _MixMonoToStereo_1TO2_32;
+		case paFloat32: return _MixMonoToStereo_1TO2_32f;
+		}
+		break;
+
+	case MIX_DIR__2TO1:
+		switch (format & ~paNonInterleaved)
+		{
+		case paUInt8:	return _MixMonoToStereo_2TO1_8;
+		case paInt16:	return _MixMonoToStereo_2TO1_16;
+		case paInt24:	return _MixMonoToStereo_2TO1_24;
+		case paInt32:	return _MixMonoToStereo_2TO1_32;
+		case paFloat32: return _MixMonoToStereo_2TO1_32f;
+		}
+		break;
+
+	case MIX_DIR__2TO1_L:
+		switch (format & ~paNonInterleaved)
+		{
+		case paUInt8:	return _MixMonoToStereo_2TO1_8_L;
+		case paInt16:	return _MixMonoToStereo_2TO1_16_L;
+		case paInt24:	return _MixMonoToStereo_2TO1_24_L;
+		case paInt32:	return _MixMonoToStereo_2TO1_32_L;
+		case paFloat32: return _MixMonoToStereo_2TO1_32f_L;
+		}
+		break;
+	}
+
+	return NULL;
+}
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaWasapiHostApiRepresentation *paWasapi;
+    PaDeviceInfo *deviceInfoArray;
+    HRESULT hr = S_OK;
+    IMMDeviceCollection* pEndPoints = NULL;
+	UINT i;
+
+    if (!SetupAVRT())
+	{
+        PRINT(("WASAPI: No AVRT! (not VISTA?)"));
+        return paNoError;
+    }
+
+    paWasapi = (PaWasapiHostApiRepresentation *)PaUtil_AllocateMemory( sizeof(PaWasapiHostApiRepresentation) );
+    if (paWasapi == NULL)
+	{
+        result = paInsufficientMemory;
+        goto error;
+    }
+	
+    memset( paWasapi, 0, sizeof(PaWasapiHostApiRepresentation) ); /* ensure all fields are zeroed. especially paWasapi->allocations */
+
+    result = PaWinUtil_CoInitialize( paWASAPI, &paWasapi->comInitializationResult );
+    if( result != paNoError )
+    {
+        goto error;
+    }
+
+    paWasapi->allocations = PaUtil_CreateAllocationGroup();
+    if (paWasapi->allocations == NULL)
+	{
+        result = paInsufficientMemory;
+        goto error;
+    }
+
+    *hostApi                             = &paWasapi->inheritedHostApiRep;
+    (*hostApi)->info.structVersion		 = 1;
+    (*hostApi)->info.type				 = paWASAPI;
+    (*hostApi)->info.name				 = "Windows WASAPI";
+    (*hostApi)->info.deviceCount		 = 0;
+    (*hostApi)->info.defaultInputDevice	 = paNoDevice;
+    (*hostApi)->info.defaultOutputDevice = paNoDevice;
+
+    paWasapi->enumerator = NULL;
+    hr = CoCreateInstance(&pa_CLSID_IMMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER,
+             &pa_IID_IMMDeviceEnumerator, (void **)&paWasapi->enumerator);
+    
+	// We need to set the result to a value otherwise we will return paNoError
+	// [IF_FAILED_JUMP(hResult, error);]
+	IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+    // getting default device ids in the eMultimedia "role"
+    {
+        {
+            IMMDevice *defaultRenderer = NULL;
+            hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(paWasapi->enumerator, eRender, eMultimedia, &defaultRenderer);
+            if (hr != S_OK)
+			{
+				if (hr != E_NOTFOUND) {
+					// We need to set the result to a value otherwise we will return paNoError
+					// [IF_FAILED_JUMP(hResult, error);]
+					IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+				}
+			}
+			else
+			{
+				WCHAR *pszDeviceId = NULL;
+				hr = IMMDevice_GetId(defaultRenderer, &pszDeviceId);
+				// We need to set the result to a value otherwise we will return paNoError
+				// [IF_FAILED_JUMP(hResult, error);]
+				IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+				wcsncpy(paWasapi->defaultRenderer, pszDeviceId, MAX_STR_LEN-1);
+				CoTaskMemFree(pszDeviceId);
+				IMMDevice_Release(defaultRenderer);
+			}
+        }
+
+        {
+            IMMDevice *defaultCapturer = NULL;
+            hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(paWasapi->enumerator, eCapture, eMultimedia, &defaultCapturer);
+            if (hr != S_OK)
+			{
+				if (hr != E_NOTFOUND) {
+					// We need to set the result to a value otherwise we will return paNoError
+					// [IF_FAILED_JUMP(hResult, error);]
+					IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+				}
+			}
+			else
+			{
+				WCHAR *pszDeviceId = NULL;
+				hr = IMMDevice_GetId(defaultCapturer, &pszDeviceId);
+				// We need to set the result to a value otherwise we will return paNoError
+				// [IF_FAILED_JUMP(hResult, error);]
+				IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+				wcsncpy(paWasapi->defaultCapturer, pszDeviceId, MAX_STR_LEN-1);
+				CoTaskMemFree(pszDeviceId);
+				IMMDevice_Release(defaultCapturer);
+			}
+        }
+    }
+
+    hr = IMMDeviceEnumerator_EnumAudioEndpoints(paWasapi->enumerator, eAll, DEVICE_STATE_ACTIVE, &pEndPoints);
+	// We need to set the result to a value otherwise we will return paNoError
+	// [IF_FAILED_JUMP(hResult, error);]
+	IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+    hr = IMMDeviceCollection_GetCount(pEndPoints, &paWasapi->deviceCount);
+	// We need to set the result to a value otherwise we will return paNoError
+	// [IF_FAILED_JUMP(hResult, error);]
+	IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+    paWasapi->devInfo = (PaWasapiDeviceInfo *)PaUtil_AllocateMemory(sizeof(PaWasapiDeviceInfo) * paWasapi->deviceCount);
+	for (i = 0; i < paWasapi->deviceCount; ++i)
+		memset(&paWasapi->devInfo[i], 0, sizeof(PaWasapiDeviceInfo));
+
+    if (paWasapi->deviceCount > 0)
+    {
+        (*hostApi)->deviceInfos = (PaDeviceInfo **)PaUtil_GroupAllocateMemory(
+                paWasapi->allocations, sizeof(PaDeviceInfo *) * paWasapi->deviceCount);
+        if ((*hostApi)->deviceInfos == NULL)
+		{
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        /* allocate all device info structs in a contiguous block */
+        deviceInfoArray = (PaDeviceInfo *)PaUtil_GroupAllocateMemory(
+                paWasapi->allocations, sizeof(PaDeviceInfo) * paWasapi->deviceCount);
+        if (deviceInfoArray == NULL)
+		{
+            result = paInsufficientMemory;
+            goto error;
+        }
+
+        for (i = 0; i < paWasapi->deviceCount; ++i)
+		{
+			DWORD state				  = 0;
+            PaDeviceInfo *deviceInfo  = &deviceInfoArray[i];
+            deviceInfo->structVersion = 2;
+            deviceInfo->hostApi       = hostApiIndex;
+
+			PA_DEBUG(("WASAPI: device idx: %02d\n", i));
+			PA_DEBUG(("WASAPI: ---------------\n"));
+
+            hr = IMMDeviceCollection_Item(pEndPoints, i, &paWasapi->devInfo[i].device);
+			// We need to set the result to a value otherwise we will return paNoError
+			// [IF_FAILED_JUMP(hResult, error);]
+			IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+            // getting ID
+            {
+                WCHAR *pszDeviceId = NULL;
+                hr = IMMDevice_GetId(paWasapi->devInfo[i].device, &pszDeviceId);
+				// We need to set the result to a value otherwise we will return paNoError
+				// [IF_FAILED_JUMP(hr, error);]
+				IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                wcsncpy(paWasapi->devInfo[i].szDeviceID, pszDeviceId, MAX_STR_LEN-1);
+                CoTaskMemFree(pszDeviceId);
+
+                if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultCapturer) == 0)
+				{// we found the default input!
+                    (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+                }
+                if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultRenderer) == 0)
+				{// we found the default output!
+                    (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+                }
+            }
+
+            hr = IMMDevice_GetState(paWasapi->devInfo[i].device, &paWasapi->devInfo[i].state);
+			// We need to set the result to a value otherwise we will return paNoError
+			// [IF_FAILED_JUMP(hResult, error);]
+			IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+            if (paWasapi->devInfo[i].state != DEVICE_STATE_ACTIVE)
+			{
+                PRINT(("WASAPI device: %d is not currently available (state:%d)\n",i,state));
+            }
+
+            {
+                IPropertyStore *pProperty;
+                hr = IMMDevice_OpenPropertyStore(paWasapi->devInfo[i].device, STGM_READ, &pProperty);
+				// We need to set the result to a value otherwise we will return paNoError
+				// [IF_FAILED_JUMP(hResult, error);]
+				IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+                // "Friendly" Name
+                {
+					char *deviceName;
+                    PROPVARIANT value;
+                    PropVariantInit(&value);
+                    hr = IPropertyStore_GetValue(pProperty, &PKEY_Device_FriendlyName, &value);
+					// We need to set the result to a value otherwise we will return paNoError
+					// [IF_FAILED_JUMP(hResult, error);]
+					IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+                    deviceInfo->name = NULL;
+                    deviceName = (char *)PaUtil_GroupAllocateMemory(paWasapi->allocations, MAX_STR_LEN + 1);
+                    if (deviceName == NULL)
+					{
+                        result = paInsufficientMemory;
+                        goto error;
+                    }
+					if (value.pwszVal)
+						WideCharToMultiByte(CP_UTF8, 0, value.pwszVal, (int)wcslen(value.pwszVal), deviceName, MAX_STR_LEN-1, 0, 0);
+					else
+						_snprintf(deviceName, MAX_STR_LEN-1, "baddev%d", i);
+                    deviceInfo->name = deviceName;
+                    PropVariantClear(&value);
+					PA_DEBUG(("WASAPI:%d| name[%s]\n", i, deviceInfo->name));
+                }
+
+                // Default format
+                {
+                    PROPVARIANT value;
+                    PropVariantInit(&value);
+                    hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEngine_DeviceFormat, &value);
+					// We need to set the result to a value otherwise we will return paNoError
+					// [IF_FAILED_JUMP(hResult, error);]
+					IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+					memcpy(&paWasapi->devInfo[i].DefaultFormat, value.blob.pBlobData, min(sizeof(paWasapi->devInfo[i].DefaultFormat), value.blob.cbSize));
+                    // cleanup
+                    PropVariantClear(&value);
+                }
+
+                // Formfactor
+                {
+                    PROPVARIANT value;
+                    PropVariantInit(&value);
+                    hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEndpoint_FormFactor, &value);
+					// We need to set the result to a value otherwise we will return paNoError
+					// [IF_FAILED_JUMP(hResult, error);]
+					IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+					// set
+					#if defined(DUMMYUNIONNAME) && defined(NONAMELESSUNION)
+						// avoid breaking strict-aliasing rules in such line: (EndpointFormFactor)(*((UINT *)(((WORD *)&value.wReserved3)+1)));
+						UINT v;
+						memcpy(&v, (((WORD *)&value.wReserved3)+1), sizeof(v));
+						paWasapi->devInfo[i].formFactor = (EndpointFormFactor)v;
+					#else
+						paWasapi->devInfo[i].formFactor = (EndpointFormFactor)value.uintVal;
+					#endif
+					PA_DEBUG(("WASAPI:%d| form-factor[%d]\n", i, paWasapi->devInfo[i].formFactor));
+                    // cleanup
+                    PropVariantClear(&value);
+                }
+
+				SAFE_RELEASE(pProperty);
+            }
+
+
+            // Endpoint data
+            {
+                IMMEndpoint *endpoint = NULL;
+                hr = IMMDevice_QueryInterface(paWasapi->devInfo[i].device, &pa_IID_IMMEndpoint, (void **)&endpoint);
+                if (SUCCEEDED(hr))
+				{
+                    hr = IMMEndpoint_GetDataFlow(endpoint, &paWasapi->devInfo[i].flow);
+                    SAFE_RELEASE(endpoint);
+                }
+            }
+
+            // Getting a temporary IAudioClient for more fields
+            // we make sure NOT to call Initialize yet!
+            {
+                IAudioClient *tmpClient = NULL;
+
+                hr = IMMDevice_Activate(paWasapi->devInfo[i].device, &pa_IID_IAudioClient,
+					CLSCTX_INPROC_SERVER, NULL, (void **)&tmpClient);
+				// We need to set the result to a value otherwise we will return paNoError
+				// [IF_FAILED_JUMP(hResult, error);]
+				IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+                hr = IAudioClient_GetDevicePeriod(tmpClient,
+                    &paWasapi->devInfo[i].DefaultDevicePeriod,
+                    &paWasapi->devInfo[i].MinimumDevicePeriod);
+				// We need to set the result to a value otherwise we will return paNoError
+				// [IF_FAILED_JUMP(hResult, error);]
+				IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
+
+                //hr = tmpClient->GetMixFormat(&paWasapi->devInfo[i].MixFormat);
+
+				// Release client
+				SAFE_RELEASE(tmpClient);
+
+				if (hr != S_OK)
+				{
+					//davidv: this happened with my hardware, previously for that same device in DirectSound:
+					//Digital Output (Realtek AC'97 Audio)'s GUID: {0x38f2cf50,0x7b4c,0x4740,0x86,0xeb,0xd4,0x38,0x66,0xd8,0xc8, 0x9f}
+					//so something must be _really_ wrong with this device, TODO handle this better. We kind of need GetMixFormat
+					LogHostError(hr);
+					// We need to set the result to a value otherwise we will return paNoError
+					result = paInternalError;
+					goto error;
+				}
+            }
+
+            // we can now fill in portaudio device data
+            deviceInfo->maxInputChannels  = 0;
+            deviceInfo->maxOutputChannels = 0;
+			deviceInfo->defaultSampleRate = paWasapi->devInfo[i].DefaultFormat.Format.nSamplesPerSec;
+            switch (paWasapi->devInfo[i].flow)
+			{
+			case eRender: {
+                deviceInfo->maxOutputChannels		 = paWasapi->devInfo[i].DefaultFormat.Format.nChannels;
+                deviceInfo->defaultHighOutputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod);
+                deviceInfo->defaultLowOutputLatency  = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod);
+				PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", i, (UINT32)deviceInfo->defaultSampleRate,
+					deviceInfo->maxOutputChannels, (float)deviceInfo->defaultHighOutputLatency, (float)deviceInfo->defaultLowOutputLatency));
+				break;}
+			case eCapture: {
+                deviceInfo->maxInputChannels		= paWasapi->devInfo[i].DefaultFormat.Format.nChannels;
+                deviceInfo->defaultHighInputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod);
+                deviceInfo->defaultLowInputLatency  = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod);
+				PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", i, (UINT32)deviceInfo->defaultSampleRate,
+					deviceInfo->maxInputChannels, (float)deviceInfo->defaultHighInputLatency, (float)deviceInfo->defaultLowInputLatency));
+				break; }
+            default:
+                PRINT(("WASAPI:%d| bad Data Flow!\n", i));
+				// We need to set the result to a value otherwise we will return paNoError
+				result = paInternalError;
+                //continue; // do not skip from list, allow to initialize
+            break;
+            }
+
+            (*hostApi)->deviceInfos[i] = deviceInfo;
+            ++(*hostApi)->info.deviceCount;
+        }
+    }
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    PaUtil_InitializeStreamInterface( &paWasapi->callbackStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &paWasapi->blockingStreamInterface, CloseStream, StartStream,
+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+
+	// findout if platform workaround is required
+	paWasapi->useWOW64Workaround = UseWOW64Workaround();
+
+    SAFE_RELEASE(pEndPoints);
+
+	PRINT(("WASAPI: initialized ok\n"));
+
+    return paNoError;
+
+error:
+
+	PRINT(("WASAPI: failed %s error[%d|%s]\n", __FUNCTION__, result, Pa_GetErrorText(result)));
+
+    SAFE_RELEASE(pEndPoints);
+
+	Terminate((PaUtilHostApiRepresentation *)paWasapi);
+
+	// Safety if error was not set so that we do not think initialize was a success
+	if (result == paNoError) {
+		result = paInternalError;
+	}
+
+    return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static void Terminate( PaUtilHostApiRepresentation *hostApi )
+{
+	UINT i;
+    PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
+	if (paWasapi == NULL)
+		return;
+
+	// Release IMMDeviceEnumerator
+    SAFE_RELEASE(paWasapi->enumerator);
+
+    for (i = 0; i < paWasapi->deviceCount; ++i)
+	{
+        PaWasapiDeviceInfo *info = &paWasapi->devInfo[i];
+        SAFE_RELEASE(info->device);
+
+		//if (info->MixFormat)
+        //    CoTaskMemFree(info->MixFormat);
+    }
+    PaUtil_FreeMemory(paWasapi->devInfo);
+
+    if (paWasapi->allocations)
+	{
+        PaUtil_FreeAllAllocations(paWasapi->allocations);
+        PaUtil_DestroyAllocationGroup(paWasapi->allocations);
+    }
+
+    PaWinUtil_CoUninitialize( paWASAPI, &paWasapi->comInitializationResult );
+
+    PaUtil_FreeMemory(paWasapi);
+
+	// Close AVRT
+	CloseAVRT();
+}
+
+// ------------------------------------------------------------------------------------------
+static PaWasapiHostApiRepresentation *_GetHostApi(PaError *_error)
+{
+	PaError error;
+
+	PaUtilHostApiRepresentation *pApi;
+	if ((error = PaUtil_GetHostApiRepresentation(&pApi, paWASAPI)) != paNoError)
+	{
+		if (_error != NULL)
+			(*_error) = error;
+
+		return NULL;
+	}
+	return (PaWasapiHostApiRepresentation *)pApi;
+}
+
+// ------------------------------------------------------------------------------------------
+int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int nFormatSize, PaDeviceIndex nDevice )
+{
+	PaError ret;
+	PaWasapiHostApiRepresentation *paWasapi;
+	UINT32 size;
+	PaDeviceIndex index;
+
+	if (pFormat == NULL)
+		return paBadBufferPtr;
+	if (nFormatSize <= 0)
+		return paBufferTooSmall;
+
+	// Get API
+	paWasapi = _GetHostApi(&ret);
+	if (paWasapi == NULL)
+		return ret;
+
+	// Get device index
+	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+	// Validate index
+	if ((UINT32)index >= paWasapi->deviceCount)
+		return paInvalidDevice;
+
+	size = min(nFormatSize, (UINT32)sizeof(paWasapi->devInfo[ index ].DefaultFormat));
+	memcpy(pFormat, &paWasapi->devInfo[ index ].DefaultFormat, size);
+
+	return size;
+}
+
+// ------------------------------------------------------------------------------------------
+int PaWasapi_GetDeviceRole( PaDeviceIndex nDevice )
+{
+	PaError ret;
+	PaDeviceIndex index;
+
+	// Get API
+	PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
+	if (paWasapi == NULL)
+		return paNotInitialized;
+
+	// Get device index
+	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+	// Validate index
+	if ((UINT32)index >= paWasapi->deviceCount)
+		return paInvalidDevice;
+
+	return paWasapi->devInfo[ index ].formFactor;
+}
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_GetFramesPerHostBuffer( PaStream *pStream, unsigned int *nInput, unsigned int *nOutput )
+{
+    PaWasapiStream *stream = (PaWasapiStream *)pStream;
+	if (stream == NULL)
+		return paBadStreamPtr;
+
+	if (nInput != NULL)
+		(*nInput) = stream->in.framesPerHostCallback;
+
+	if (nOutput != NULL)
+		(*nOutput) = stream->out.framesPerHostCallback;
+
+	return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+static void LogWAVEFORMATEXTENSIBLE(const WAVEFORMATEXTENSIBLE *in)
+{
+    const WAVEFORMATEX *old = (WAVEFORMATEX *)in;
+	switch (old->wFormatTag)
+	{
+	case WAVE_FORMAT_EXTENSIBLE: {
+
+		PRINT(("wFormatTag     =WAVE_FORMAT_EXTENSIBLE\n"));
+
+		if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
+		{
+			PRINT(("SubFormat      =KSDATAFORMAT_SUBTYPE_IEEE_FLOAT\n"));
+		}
+		else
+		if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
+		{
+			PRINT(("SubFormat      =KSDATAFORMAT_SUBTYPE_PCM\n"));
+		}
+		else
+		{
+			PRINT(("SubFormat      =CUSTOM GUID{%d:%d:%d:%d%d%d%d%d%d%d%d}\n",
+										in->SubFormat.Data1,
+										in->SubFormat.Data2,
+										in->SubFormat.Data3,
+										(int)in->SubFormat.Data4[0],
+										(int)in->SubFormat.Data4[1],
+										(int)in->SubFormat.Data4[2],
+										(int)in->SubFormat.Data4[3],
+										(int)in->SubFormat.Data4[4],
+										(int)in->SubFormat.Data4[5],
+										(int)in->SubFormat.Data4[6],
+										(int)in->SubFormat.Data4[7]));
+		}
+		PRINT(("Samples.wValidBitsPerSample =%d\n",  in->Samples.wValidBitsPerSample));
+		PRINT(("dwChannelMask  =0x%X\n",in->dwChannelMask));
+
+		break; }
+
+	case WAVE_FORMAT_PCM:        PRINT(("wFormatTag     =WAVE_FORMAT_PCM\n")); break;
+	case WAVE_FORMAT_IEEE_FLOAT: PRINT(("wFormatTag     =WAVE_FORMAT_IEEE_FLOAT\n")); break;
+	default: 
+		PRINT(("wFormatTag     =UNKNOWN(%d)\n",old->wFormatTag)); break;
+	}
+
+	PRINT(("nChannels      =%d\n",old->nChannels));
+	PRINT(("nSamplesPerSec =%d\n",old->nSamplesPerSec));
+	PRINT(("nAvgBytesPerSec=%d\n",old->nAvgBytesPerSec));
+	PRINT(("nBlockAlign    =%d\n",old->nBlockAlign));
+	PRINT(("wBitsPerSample =%d\n",old->wBitsPerSample));
+	PRINT(("cbSize         =%d\n",old->cbSize));
+}
+
+// ------------------------------------------------------------------------------------------
+static PaSampleFormat WaveToPaFormat(const WAVEFORMATEXTENSIBLE *in)
+{
+    const WAVEFORMATEX *old = (WAVEFORMATEX *)in;
+
+    switch (old->wFormatTag)
+	{
+    case WAVE_FORMAT_EXTENSIBLE: {
+        if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
+		{
+            if (in->Samples.wValidBitsPerSample == 32)
+                return paFloat32;
+        }
+        else
+		if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
+		{
+            switch (old->wBitsPerSample)
+			{
+                case 32: return paInt32;
+                case 24: return paInt24;
+                case  8: return paUInt8;
+                case 16: return paInt16;
+            }
+        }
+		break; }
+
+    case WAVE_FORMAT_IEEE_FLOAT:
+		return paFloat32;
+
+    case WAVE_FORMAT_PCM: {
+        switch (old->wBitsPerSample)
+		{
+            case 32: return paInt32;
+            case 24: return paInt24;
+            case  8: return paUInt8;
+            case 16: return paInt16;
+        }
+		break; }
+    }
+
+    return paCustomFormat;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError MakeWaveFormatFromParams(WAVEFORMATEXTENSIBLE *wavex, const PaStreamParameters *params,
+									double sampleRate)
+{
+	WORD bitsPerSample;
+	WAVEFORMATEX *old;
+	DWORD channelMask = 0;
+	PaWasapiStreamInfo *streamInfo = (PaWasapiStreamInfo *)params->hostApiSpecificStreamInfo;
+
+	// Get user assigned channel mask
+	if ((streamInfo != NULL) && (streamInfo->flags & paWinWasapiUseChannelMask))
+		channelMask = streamInfo->channelMask;
+
+	// Convert PaSampleFormat to bits per sample
+	if ((bitsPerSample = PaSampleFormatToBitsPerSample(params->sampleFormat)) == 0)
+		return paSampleFormatNotSupported;
+
+    memset(wavex, 0, sizeof(*wavex));
+
+    old					 = (WAVEFORMATEX *)wavex;
+    old->nChannels       = (WORD)params->channelCount;
+    old->nSamplesPerSec  = (DWORD)sampleRate;
+	if ((old->wBitsPerSample = bitsPerSample) > 16)
+	{
+		old->wBitsPerSample = 32; // 20 or 24 bits must go in 32 bit containers (ints)
+	}
+    old->nBlockAlign     = (old->nChannels * (old->wBitsPerSample/8));
+    old->nAvgBytesPerSec = (old->nSamplesPerSec * old->nBlockAlign);
+
+    // WAVEFORMATEX
+    if ((params->channelCount <= 2) && ((bitsPerSample == 16) || (bitsPerSample == 8)))
+	{
+        old->cbSize		= 0;
+        old->wFormatTag	= WAVE_FORMAT_PCM;
+    }
+    // WAVEFORMATEXTENSIBLE
+    else
+	{
+        old->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
+        old->cbSize		= sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
+
+        if ((params->sampleFormat & ~paNonInterleaved) == paFloat32)
+            wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
+        else
+            wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+
+        wavex->Samples.wValidBitsPerSample = bitsPerSample; //no extra padding!
+
+		// Set channel mask
+		if (channelMask != 0)
+		{
+			wavex->dwChannelMask = channelMask;
+		}
+		else
+		{
+			switch (params->channelCount)
+			{
+			case 1:  wavex->dwChannelMask = KSAUDIO_SPEAKER_MONO; break;
+			case 2:  wavex->dwChannelMask = KSAUDIO_SPEAKER_STEREO; break;
+			case 3:  wavex->dwChannelMask = KSAUDIO_SPEAKER_STEREO|SPEAKER_LOW_FREQUENCY; break;
+			case 4:  wavex->dwChannelMask = KSAUDIO_SPEAKER_QUAD; break;
+			case 5:  wavex->dwChannelMask = KSAUDIO_SPEAKER_QUAD|SPEAKER_LOW_FREQUENCY; break;
+#ifdef KSAUDIO_SPEAKER_5POINT1_SURROUND
+			case 6:  wavex->dwChannelMask = KSAUDIO_SPEAKER_5POINT1_SURROUND; break;
+#else
+			case 6:  wavex->dwChannelMask = KSAUDIO_SPEAKER_5POINT1; break;
+#endif
+#ifdef KSAUDIO_SPEAKER_5POINT1_SURROUND
+			case 7:  wavex->dwChannelMask = KSAUDIO_SPEAKER_5POINT1_SURROUND|SPEAKER_BACK_CENTER; break;
+#else
+			case 7:  wavex->dwChannelMask = KSAUDIO_SPEAKER_5POINT1|SPEAKER_BACK_CENTER; break;
+#endif	
+#ifdef KSAUDIO_SPEAKER_7POINT1_SURROUND
+			case 8:  wavex->dwChannelMask = KSAUDIO_SPEAKER_7POINT1_SURROUND; break;
+#else
+			case 8:  wavex->dwChannelMask = KSAUDIO_SPEAKER_7POINT1; break;
+#endif
+
+			default: wavex->dwChannelMask = 0;
+			}
+		}
+	}
+    return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+/*static void wasapiFillWFEXT( WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount)
+{
+    PA_DEBUG(( "sampleFormat = %lx\n" , sampleFormat ));
+    PA_DEBUG(( "sampleRate = %f\n" , sampleRate ));
+    PA_DEBUG(( "chanelCount = %d\n", channelCount ));
+
+    pwfext->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
+    pwfext->Format.nChannels = (WORD)channelCount;
+    pwfext->Format.nSamplesPerSec = (DWORD)sampleRate;
+    if(channelCount == 1)
+        pwfext->dwChannelMask = KSAUDIO_SPEAKER_DIRECTOUT;
+    else
+        pwfext->dwChannelMask = KSAUDIO_SPEAKER_STEREO;
+    if(sampleFormat == paFloat32)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
+        pwfext->Format.wBitsPerSample = 32;
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 32;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
+    }
+    else if(sampleFormat == paInt32)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
+        pwfext->Format.wBitsPerSample = 32;
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 32;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+    }
+    else if(sampleFormat == paInt24)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
+        pwfext->Format.wBitsPerSample = 32; // 24-bit in 32-bit int container
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 24;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+    }
+    else if(sampleFormat == paInt16)
+    {
+        pwfext->Format.nBlockAlign = (WORD)(channelCount * 2);
+        pwfext->Format.wBitsPerSample = 16;
+        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
+        pwfext->Samples.wValidBitsPerSample = 16;
+        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
+    }
+    pwfext->Format.nAvgBytesPerSec = pwfext->Format.nSamplesPerSec * pwfext->Format.nBlockAlign;
+}*/
+
+// ------------------------------------------------------------------------------------------
+static PaError GetClosestFormat(IAudioClient *myClient, double sampleRate,
+	const PaStreamParameters *_params, AUDCLNT_SHAREMODE shareMode, WAVEFORMATEXTENSIBLE *outWavex,
+	BOOL output)
+{
+	PaError answer                   = paInvalidSampleRate;
+	WAVEFORMATEX *sharedClosestMatch = NULL;
+	HRESULT hr                       = !S_OK;
+	PaStreamParameters params       = (*_params);
+
+	/* It was not noticed that 24-bit Input producing no output while device accepts this format.
+	   To fix this issue let's ask for 32-bits and let PA converters convert host 32-bit data
+	   to 24-bit for user-space. The bug concerns Vista, if Windows 7 supports 24-bits for Input
+	   please report to PortAudio developers to exclude Windows 7.
+	*/
+	/*if ((params.sampleFormat == paInt24) && (output == FALSE))
+		params.sampleFormat = paFloat32;*/ // <<< The silence was due to missing Int32_To_Int24_Dither implementation
+
+    MakeWaveFormatFromParams(outWavex, &params, sampleRate);
+
+	hr = IAudioClient_IsFormatSupported(myClient, shareMode, &outWavex->Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+	if (hr == S_OK)
+		answer = paFormatIsSupported;
+    else
+	if (sharedClosestMatch)
+	{
+		WORD bitsPerSample;
+        WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)sharedClosestMatch;
+
+		GUID subf_guid = GUID_NULL;
+		if (sharedClosestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
+		{
+			memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEXTENSIBLE));
+			subf_guid = ext->SubFormat;
+		}
+		else
+			memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEX));
+
+        CoTaskMemFree(sharedClosestMatch);
+
+		// Make supported by default
+		answer = paFormatIsSupported;
+
+		// Validate SampleRate
+		if ((DWORD)sampleRate != outWavex->Format.nSamplesPerSec)
+			return paInvalidSampleRate;
+
+		// Validate Channel count
+		if ((WORD)params.channelCount != outWavex->Format.nChannels)
+		{
+			// If mono, then driver does not support 1 channel, we use internal workaround
+			// of tiny software mixing functionality, e.g. we provide to user buffer 1 channel
+			// but then mix into 2 for device buffer
+			if ((params.channelCount == 1) && (outWavex->Format.nChannels == 2))
+				return paFormatIsSupported;
+			else
+				return paInvalidChannelCount;
+		}
+
+		// Validate Sample format
+		if ((bitsPerSample = PaSampleFormatToBitsPerSample(params.sampleFormat)) == 0)
+			return paSampleFormatNotSupported;
+
+		// Validate Sample format: bit size (WASAPI does not limit 'bit size')
+		//if (bitsPerSample != outWavex->Format.wBitsPerSample)
+		//	return paSampleFormatNotSupported;
+
+		// Validate Sample format: paFloat32 (WASAPI does not limit 'bit type')
+		//if ((params->sampleFormat == paFloat32) && (subf_guid != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
+		//	return paSampleFormatNotSupported;
+
+		// Validate Sample format: paInt32 (WASAPI does not limit 'bit type')
+		//if ((params->sampleFormat == paInt32) && (subf_guid != KSDATAFORMAT_SUBTYPE_PCM))
+		//	return paSampleFormatNotSupported;
+	}
+	else
+	{
+		static const int BestToWorst[] = { paFloat32, paInt24, paInt16 };
+		int i;
+
+		// Try combination stereo and we will use built-in mono-stereo mixer then
+		if (params.channelCount == 1)
+		{
+			WAVEFORMATEXTENSIBLE stereo = { 0 };
+
+			PaStreamParameters stereo_params = params;
+			stereo_params.channelCount = 2;
+
+			MakeWaveFormatFromParams(&stereo, &stereo_params, sampleRate);
+
+			hr = IAudioClient_IsFormatSupported(myClient, shareMode, &stereo.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+			if (hr == S_OK)
+			{
+				memcpy(outWavex, &stereo, sizeof(WAVEFORMATEXTENSIBLE));
+				CoTaskMemFree(sharedClosestMatch);
+				return (answer = paFormatIsSupported);
+			}
+
+			// Try selecting suitable sample type
+			for (i = 0; i < STATIC_ARRAY_SIZE(BestToWorst); ++i)
+			{
+				WAVEFORMATEXTENSIBLE sample = { 0 };
+
+				PaStreamParameters sample_params = stereo_params;
+				sample_params.sampleFormat = BestToWorst[i];
+
+				MakeWaveFormatFromParams(&sample, &sample_params, sampleRate);
+
+				hr = IAudioClient_IsFormatSupported(myClient, shareMode, &sample.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+				if (hr == S_OK)
+				{
+					memcpy(outWavex, &sample, sizeof(WAVEFORMATEXTENSIBLE));
+					CoTaskMemFree(sharedClosestMatch);
+					return (answer = paFormatIsSupported);
+				}
+			}
+		}
+
+		// Try selecting suitable sample type
+		for (i = 0; i < STATIC_ARRAY_SIZE(BestToWorst); ++i)
+		{
+			WAVEFORMATEXTENSIBLE spfmt = { 0 };
+
+			PaStreamParameters spfmt_params = params;
+			spfmt_params.sampleFormat = BestToWorst[i];
+
+			MakeWaveFormatFromParams(&spfmt, &spfmt_params, sampleRate);
+
+			hr = IAudioClient_IsFormatSupported(myClient, shareMode, &spfmt.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
+			if (hr == S_OK)
+			{
+				memcpy(outWavex, &spfmt, sizeof(WAVEFORMATEXTENSIBLE));
+				CoTaskMemFree(sharedClosestMatch);
+				answer = paFormatIsSupported;
+				break;
+			}
+		}
+
+		// Nothing helped
+		LogHostError(hr);
+	}
+
+	return answer;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsStreamParamsValid(struct PaUtilHostApiRepresentation *hostApi,
+                                   const  PaStreamParameters *inputParameters,
+                                   const  PaStreamParameters *outputParameters,
+                                   double sampleRate)
+{
+	if (hostApi == NULL)
+		return paHostApiNotFound;
+	if ((UINT32)sampleRate == 0)
+		return paInvalidSampleRate;
+
+	if (inputParameters != NULL)
+    {
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+		if (inputParameters->sampleFormat & paCustomFormat)
+            return paSampleFormatNotSupported;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if (inputParameters->device == paUseHostApiSpecificDeviceSpecification)
+            return paInvalidDevice;
+
+        /* check that input device can support inputChannelCount */
+        if (inputParameters->channelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels)
+            return paInvalidChannelCount;
+
+        /* validate inputStreamInfo */
+        if (inputParameters->hostApiSpecificStreamInfo)
+		{
+			PaWasapiStreamInfo *inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
+	        if ((inputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
+	            (inputStreamInfo->version != 1) ||
+                (inputStreamInfo->hostApiType != paWASAPI))
+	        {
+	            return paIncompatibleHostApiSpecificStreamInfo;
+	        }
+		}
+
+        return paNoError;
+    }
+
+    if (outputParameters != NULL)
+    {
+        /* all standard sample formats are supported by the buffer adapter,
+            this implementation doesn't support any custom sample formats */
+        if (outputParameters->sampleFormat & paCustomFormat)
+            return paSampleFormatNotSupported;
+
+        /* unless alternate device specification is supported, reject the use of
+            paUseHostApiSpecificDeviceSpecification */
+        if (outputParameters->device == paUseHostApiSpecificDeviceSpecification)
+            return paInvalidDevice;
+
+        /* check that output device can support outputChannelCount */
+        if (outputParameters->channelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels)
+            return paInvalidChannelCount;
+
+        /* validate outputStreamInfo */
+        if(outputParameters->hostApiSpecificStreamInfo)
+        {
+			PaWasapiStreamInfo *outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
+	        if ((outputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
+	            (outputStreamInfo->version != 1) ||
+                (outputStreamInfo->hostApiType != paWASAPI))
+	        {
+	            return paIncompatibleHostApiSpecificStreamInfo;
+	        }
+        }
+
+		return paNoError;
+    }
+
+	return (inputParameters || outputParameters ? paNoError : paInternalError);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const  PaStreamParameters *inputParameters,
+                                  const  PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+	IAudioClient *tmpClient = NULL;
+	PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
+	PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
+
+	// Validate PaStreamParameters
+	PaError error;
+	if ((error = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
+		return error;
+
+    if (inputParameters != NULL)
+    {
+		WAVEFORMATEXTENSIBLE wavex;
+		HRESULT hr;
+		PaError answer;
+		AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
+		inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
+
+		if (inputStreamInfo && (inputStreamInfo->flags & paWinWasapiExclusive))
+			shareMode  = AUDCLNT_SHAREMODE_EXCLUSIVE;
+
+		hr = IMMDevice_Activate(paWasapi->devInfo[inputParameters->device].device,
+			&pa_IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, (void **)&tmpClient);
+		if (hr != S_OK)
+		{
+			LogHostError(hr);
+			return paInvalidDevice;
+		}
+
+		answer = GetClosestFormat(tmpClient, sampleRate, inputParameters, shareMode, &wavex, FALSE);
+		SAFE_RELEASE(tmpClient);
+
+		if (answer != paFormatIsSupported)
+			return answer;
+    }
+
+    if (outputParameters != NULL)
+    {
+		HRESULT hr;
+		WAVEFORMATEXTENSIBLE wavex;
+		PaError answer;
+		AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
+        outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
+
+		if (outputStreamInfo && (outputStreamInfo->flags & paWinWasapiExclusive))
+			shareMode  = AUDCLNT_SHAREMODE_EXCLUSIVE;
+
+		hr = IMMDevice_Activate(paWasapi->devInfo[outputParameters->device].device,
+			&pa_IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, (void **)&tmpClient);
+		if (hr != S_OK)
+		{
+			LogHostError(hr);
+			return paInvalidDevice;
+		}
+
+		answer = GetClosestFormat(tmpClient, sampleRate, outputParameters, shareMode, &wavex, TRUE);
+		SAFE_RELEASE(tmpClient);
+
+		if (answer != paFormatIsSupported)
+			return answer;
+    }
+
+    return paFormatIsSupported;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaUint32 PaUtil_GetFramesPerHostBuffer(PaUint32 userFramesPerBuffer, PaTime suggestedLatency, double sampleRate, PaUint32 TimerJitterMs)
+{
+	PaUint32 frames = userFramesPerBuffer + max( userFramesPerBuffer, (PaUint32)(suggestedLatency * sampleRate) );
+    frames += (PaUint32)((sampleRate * 0.001) * TimerJitterMs);
+	return frames;
+}
+
+// ------------------------------------------------------------------------------------------
+static void _RecalculateBuffersCount(PaWasapiSubStream *sub, UINT32 userFramesPerBuffer, UINT32 framesPerLatency, BOOL fullDuplex)
+{
+	// Count buffers (must be at least 1)
+	sub->buffers = (userFramesPerBuffer ? framesPerLatency / userFramesPerBuffer : 0);
+	if (sub->buffers == 0)
+		sub->buffers = 1;
+
+	// Determine amount of buffers used:
+	// - Full-duplex mode will lead to period difference, thus only 1.
+	// - Input mode, only 1, as WASAPI allows extraction of only 1 packet.
+	// - For Shared mode we use double buffering.
+	if ((sub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) || fullDuplex)
+	{
+		// Exclusive mode does not allow >1 buffers be used for Event interface, e.g. GetBuffer
+		// call must acquire max buffer size and it all must be processed.
+		if (sub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)
+			sub->userBufferAndHostMatch = 1;
+
+		// Use paUtilBoundedHostBufferSize because exclusive mode will starve and produce
+		// bad quality of audio
+		sub->buffers = 1;
+	}
+}
+
+// ------------------------------------------------------------------------------------------
+static void _CalculateAlignedPeriod(PaWasapiSubStream *pSub, UINT32 *nFramesPerLatency,
+									ALIGN_FUNC pAlignFunc)
+{
+	// Align frames to HD Audio packet size of 128 bytes for Exclusive mode only.
+	// Not aligning on Windows Vista will cause Event timeout, although Windows 7 will
+	// return AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED error to realign buffer. Aligning is necessary
+	// for Exclusive mode only! when audio data is feeded directly to hardware.
+	if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
+	{
+		(*nFramesPerLatency) = AlignFramesPerBuffer((*nFramesPerLatency),
+			pSub->wavex.Format.nSamplesPerSec, pSub->wavex.Format.nBlockAlign, pAlignFunc);
+	}
+
+	// Calculate period
+	pSub->period = MakeHnsPeriod((*nFramesPerLatency), pSub->wavex.Format.nSamplesPerSec);
+}
+
+// ------------------------------------------------------------------------------------------
+static HRESULT CreateAudioClient(PaWasapiStream *pStream, PaWasapiSubStream *pSub, BOOL output, PaError *pa_error)
+{
+	PaError error;
+    HRESULT hr;
+
+	const PaWasapiDeviceInfo *pInfo  = pSub->params.device_info;
+	const PaStreamParameters *params = &pSub->params.stream_params;
+	UINT32 framesPerLatency          = pSub->params.frames_per_buffer;
+	double sampleRate                = pSub->params.sample_rate;
+	BOOL blocking                    = pSub->params.blocking;
+	BOOL fullDuplex                  = pSub->params.full_duplex;
+
+	const UINT32 userFramesPerBuffer = framesPerLatency;
+    IAudioClient *audioClient	     = NULL;
+
+	// Assume default failure due to some reason
+	(*pa_error) = paInvalidDevice;
+
+	// Validate parameters
+    if (!pSub || !pInfo || !params)
+	{
+		(*pa_error) = paBadStreamPtr;
+        return E_POINTER;
+	}
+	if ((UINT32)sampleRate == 0)
+	{
+		(*pa_error) = paInvalidSampleRate;
+        return E_INVALIDARG;
+	}
+
+    // Get the audio client
+    hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&audioClient);
+	if (hr != S_OK)
+	{
+		(*pa_error) = paInsufficientMemory;
+		LogHostError(hr);
+		goto done;
+	}
+
+	// Get closest format
+	if ((error = GetClosestFormat(audioClient, sampleRate, params, pSub->shareMode, &pSub->wavex, output)) != paFormatIsSupported)
+	{
+		(*pa_error) = error;
+		LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+		goto done; // fail, format not supported
+	}
+
+	// Check for Mono <<>> Stereo workaround
+	if ((params->channelCount == 1) && (pSub->wavex.Format.nChannels == 2))
+	{
+		/*if (blocking)
+		{
+			LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+			goto done; // fail, blocking mode not supported
+		}*/
+
+		// select mixer
+		pSub->monoMixer = _GetMonoToStereoMixer(WaveToPaFormat(&pSub->wavex), (pInfo->flow == eRender ? MIX_DIR__1TO2 : MIX_DIR__2TO1_L));
+		if (pSub->monoMixer == NULL)
+		{
+			(*pa_error) = paInvalidChannelCount;
+			LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+			goto done; // fail, no mixer for format
+		}
+	}
+
+#if 0
+	// Add suggestd latency
+	framesPerLatency += MakeFramesFromHns(SecondsTonano100(params->suggestedLatency), pSub->wavex.Format.nSamplesPerSec);
+#else
+	// Calculate host buffer size
+	if ((pSub->shareMode != AUDCLNT_SHAREMODE_EXCLUSIVE) &&
+		(!pSub->streamFlags || ((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
+	{
+		framesPerLatency = PaUtil_GetFramesPerHostBuffer(userFramesPerBuffer,
+			params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
+			(pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
+	}
+	else
+	{
+		REFERENCE_TIME overall;
+
+		// Work 1:1 with user buffer (only polling allows to use >1)
+		framesPerLatency += MakeFramesFromHns(SecondsTonano100(params->suggestedLatency), pSub->wavex.Format.nSamplesPerSec);
+
+		// Use Polling if overall latency is > 5ms as it allows to use 100% CPU in a callback,
+		// or user specified latency parameter
+		overall = MakeHnsPeriod(framesPerLatency, pSub->wavex.Format.nSamplesPerSec);
+		if ((overall >= (106667*2)/*21.33ms*/) || ((INT32)(params->suggestedLatency*100000.0) != 0/*0.01 msec granularity*/))
+		{
+			framesPerLatency = PaUtil_GetFramesPerHostBuffer(userFramesPerBuffer,
+				params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
+				(streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
+
+			// Use Polling interface
+			pSub->streamFlags &= ~AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
+			PRINT(("WASAPI: CreateAudioClient: forcing POLL mode\n"));
+		}
+	}
+#endif
+
+	// For full-duplex output resize buffer to be the same as for input
+	if (output && fullDuplex)
+		framesPerLatency = pStream->in.framesPerHostCallback;
+
+	// Avoid 0 frames
+	if (framesPerLatency == 0)
+		framesPerLatency = MakeFramesFromHns(pInfo->DefaultDevicePeriod, pSub->wavex.Format.nSamplesPerSec);
+
+	// Exclusive Input stream renders data in 6 packets, we must set then the size of
+	// single packet, total buffer size, e.g. required latency will be PacketSize * 6
+	if (!output && (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE))
+	{
+		// Do it only for Polling mode
+		if ((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)
+		{
+			framesPerLatency /= WASAPI_PACKETS_PER_INPUT_BUFFER;
+		}
+	}
+
+	// Calculate aligned period
+	_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+
+	/*! Enforce min/max period for device in Shared mode to avoid bad audio quality.
+        Avoid doing so for Exclusive mode as alignment will suffer.
+	*/
+	if (pSub->shareMode == AUDCLNT_SHAREMODE_SHARED)
+	{
+		if (pSub->period < pInfo->DefaultDevicePeriod)
+		{
+			pSub->period = pInfo->DefaultDevicePeriod;
+			// Recalculate aligned period
+			framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+			_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+		}
+	}
+	else
+	{
+		if (pSub->period < pInfo->MinimumDevicePeriod)
+		{
+			pSub->period = pInfo->MinimumDevicePeriod;
+			// Recalculate aligned period
+			framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+			_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_FWD);
+		}
+	}
+
+	/*! Windows 7 does not allow to set latency lower than minimal device period and will
+	    return error: AUDCLNT_E_INVALID_DEVICE_PERIOD. Under Vista we enforce the same behavior
+	    manually for unified behavior on all platforms.
+	*/
+	{
+		/*!	AUDCLNT_E_BUFFER_SIZE_ERROR: Applies to Windows 7 and later.
+			Indicates that the buffer duration value requested by an exclusive-mode client is
+			out of range. The requested duration value for pull mode must not be greater than
+			500 milliseconds; for push mode the duration value must not be greater than 2 seconds.
+		*/
+		if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
+		{
+			static const REFERENCE_TIME MAX_BUFFER_EVENT_DURATION = 500  * 10000;
+			static const REFERENCE_TIME MAX_BUFFER_POLL_DURATION  = 2000 * 10000;
+
+			if (pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)	// pull mode, max 500ms
+			{
+				if (pSub->period > MAX_BUFFER_EVENT_DURATION)
+				{
+					pSub->period = MAX_BUFFER_EVENT_DURATION;
+					// Recalculate aligned period
+					framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+					_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+				}
+			}
+			else														// push mode, max 2000ms
+			{
+				if (pSub->period > MAX_BUFFER_POLL_DURATION)
+				{
+					pSub->period = MAX_BUFFER_POLL_DURATION;
+					// Recalculate aligned period
+					framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+					_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+				}
+			}
+		}
+	}
+
+	// Open the stream and associate it with an audio session
+    hr = IAudioClient_Initialize(audioClient,
+        pSub->shareMode,
+        pSub->streamFlags,
+		pSub->period,
+		(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+		&pSub->wavex.Format,
+        NULL);
+
+	/*! WASAPI is tricky on large device buffer, sometimes 2000ms can be allocated sometimes
+	    less. There is no known guaranteed level thus we make subsequent tries by decreasing
+		buffer by 100ms per try.
+	*/
+	while ((hr == E_OUTOFMEMORY) && (pSub->period > (100 * 10000)))
+	{
+		PRINT(("WASAPI: CreateAudioClient: decreasing buffer size to %d milliseconds\n", (pSub->period / 10000)));
+
+		// Decrease by 100ms and try again
+		pSub->period -= (100 * 10000);
+
+		// Recalculate aligned period
+		framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
+		_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
+
+        // Release the previous allocations
+        SAFE_RELEASE(audioClient);
+
+        // Create a new audio client
+        hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&audioClient);
+    	if (hr != S_OK)
+		{
+			(*pa_error) = paInsufficientMemory;
+			LogHostError(hr);
+			goto done;
+		}
+
+		// Open the stream and associate it with an audio session
+		hr = IAudioClient_Initialize(audioClient,
+			pSub->shareMode,
+			pSub->streamFlags,
+			pSub->period,
+			(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+			&pSub->wavex.Format,
+			NULL);
+	}
+
+	/*! WASAPI buffer size failure. Fallback to using default size.
+	*/
+	if (hr == AUDCLNT_E_BUFFER_SIZE_ERROR)
+	{
+		// Use default
+		pSub->period = pInfo->DefaultDevicePeriod;
+
+		PRINT(("WASAPI: CreateAudioClient: correcting buffer size to device default\n"));
+
+        // Release the previous allocations
+        SAFE_RELEASE(audioClient);
+
+        // Create a new audio client
+        hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&audioClient);
+    	if (hr != S_OK)
+		{
+			(*pa_error) = paInsufficientMemory;
+			LogHostError(hr);
+			goto done;
+		}
+
+		// Open the stream and associate it with an audio session
+		hr = IAudioClient_Initialize(audioClient,
+			pSub->shareMode,
+			pSub->streamFlags,
+			pSub->period,
+			(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+			&pSub->wavex.Format,
+			NULL);
+	}
+
+    /*! If the requested buffer size is not aligned. Can be triggered by Windows 7 and up.
+	    Should not be be triggered ever as we do align buffers always with _CalculateAlignedPeriod.
+	*/
+    if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
+    {
+		UINT32 frames = 0;
+
+        // Get the next aligned frame
+        hr = IAudioClient_GetBufferSize(audioClient, &frames);
+		if (hr != S_OK)
+		{
+			(*pa_error) = paInvalidDevice;
+			LogHostError(hr);
+			goto done;
+		}
+
+		PRINT(("WASAPI: CreateAudioClient: aligning buffer size to % frames\n", frames));
+
+        // Release the previous allocations
+        SAFE_RELEASE(audioClient);
+
+        // Create a new audio client
+        hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&audioClient);
+    	if (hr != S_OK)
+		{
+			(*pa_error) = paInsufficientMemory;
+			LogHostError(hr);
+			goto done;
+		}
+
+		// Get closest format
+		if ((error = GetClosestFormat(audioClient, sampleRate, params, pSub->shareMode, &pSub->wavex, output)) != paFormatIsSupported)
+		{
+			(*pa_error) = error;
+			LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT); // fail, format not supported
+			goto done;
+		}
+
+		// Check for Mono >> Stereo workaround
+		if ((params->channelCount == 1) && (pSub->wavex.Format.nChannels == 2))
+		{
+			/*if (blocking)
+			{
+				LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+				goto done; // fail, blocking mode not supported
+			}*/
+
+			// Select mixer
+			pSub->monoMixer = _GetMonoToStereoMixer(WaveToPaFormat(&pSub->wavex), (pInfo->flow == eRender ? MIX_DIR__1TO2 : MIX_DIR__2TO1_L));
+			if (pSub->monoMixer == NULL)
+			{
+				(*pa_error) = paInvalidChannelCount;
+				LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
+				goto done; // fail, no mixer for format
+			}
+		}
+
+		// Calculate period
+		pSub->period = MakeHnsPeriod(frames, pSub->wavex.Format.nSamplesPerSec);
+
+        // Open the stream and associate it with an audio session
+        hr = IAudioClient_Initialize(audioClient,
+            pSub->shareMode,
+            pSub->streamFlags,
+			pSub->period,
+			(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
+            &pSub->wavex.Format,
+            NULL);
+    	if (hr != S_OK)
+		{
+			(*pa_error) = paInvalidDevice;
+			LogHostError(hr);
+			goto done;
+		}
+    }
+    else
+	if (hr != S_OK)
+    {
+		(*pa_error) = paInvalidDevice;
+		LogHostError(hr);
+		goto done;
+    }
+
+    // Set client
+	pSub->clientParent = audioClient;
+    IAudioClient_AddRef(pSub->clientParent);
+
+	// Recalculate buffers count
+	_RecalculateBuffersCount(pSub,
+		userFramesPerBuffer,
+		MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec),
+		fullDuplex);
+
+	// No error, client is succesfully created
+	(*pa_error) = paNoError;
+
+done:
+
+    // Clean up
+    SAFE_RELEASE(audioClient);
+    return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError ActivateAudioClientOutput(PaWasapiStream *stream)
+{
+	HRESULT hr;
+	PaError result;
+
+	UINT32 maxBufferSize   = 0;
+	PaTime buffer_latency  = 0;
+	UINT32 framesPerBuffer = stream->out.params.frames_per_buffer;
+
+	// Create Audio client
+	hr = CreateAudioClient(stream, &stream->out, TRUE, &result);
+    if (hr != S_OK)
+	{
+		LogPaError(result);
+		goto error;
+    }
+	LogWAVEFORMATEXTENSIBLE(&stream->out.wavex);
+
+	// Activate volume
+	stream->outVol = NULL;
+    /*hr = info->device->Activate(
+        __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
+        (void**)&stream->outVol);
+    if (hr != S_OK)
+        return paInvalidDevice;*/
+
+    // Get max possible buffer size to check if it is not less than that we request
+    hr = IAudioClient_GetBufferSize(stream->out.clientParent, &maxBufferSize);
+    if (hr != S_OK)
+	{
+		LogHostError(hr);
+		LogPaError(result = paInvalidDevice);
+		goto error;
+	}
+
+    // Correct buffer to max size if it maxed out result of GetBufferSize
+	stream->out.bufferSize = maxBufferSize;
+
+	// Get interface latency (actually uneeded as we calculate latency from the size
+	// of maxBufferSize).
+    hr = IAudioClient_GetStreamLatency(stream->out.clientParent, &stream->out.deviceLatency);
+    if (hr != S_OK)
+	{
+		LogHostError(hr);
+		LogPaError(result = paInvalidDevice);
+		goto error;
+	}
+	//stream->out.latencySeconds = nano100ToSeconds(stream->out.deviceLatency);
+
+    // Number of frames that are required at each period
+	stream->out.framesPerHostCallback = maxBufferSize;
+
+	// Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
+	stream->out.framesPerBuffer =
+		(stream->out.userBufferAndHostMatch ? stream->out.framesPerHostCallback : framesPerBuffer);
+
+	// Calculate buffer latency
+	buffer_latency = (PaTime)maxBufferSize / stream->out.wavex.Format.nSamplesPerSec;
+
+	// Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
+	stream->out.latencySeconds = buffer_latency;
+
+	PRINT(("WASAPI::OpenStream(output): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->out.framesPerHostCallback, (float)(stream->out.latencySeconds*1000.0f), (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (stream->out.params.wow64_workaround ? "YES" : "NO"), (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
+
+	return paNoError;
+
+error:
+
+	return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError ActivateAudioClientInput(PaWasapiStream *stream)
+{
+	HRESULT hr;
+	PaError result;
+
+	UINT32 maxBufferSize   = 0;
+	PaTime buffer_latency  = 0;
+	UINT32 framesPerBuffer = stream->in.params.frames_per_buffer;
+
+	// Create Audio client
+	hr = CreateAudioClient(stream, &stream->in, FALSE, &result);
+    if (hr != S_OK)
+	{
+		LogPaError(result);
+		goto error;
+    }
+	LogWAVEFORMATEXTENSIBLE(&stream->in.wavex);
+
+	// Create volume mgr
+	stream->inVol = NULL;
+    /*hr = info->device->Activate(
+        __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
+        (void**)&stream->inVol);
+    if (hr != S_OK)
+        return paInvalidDevice;*/
+
+    // Get max possible buffer size to check if it is not less than that we request
+    hr = IAudioClient_GetBufferSize(stream->in.clientParent, &maxBufferSize);
+    if (hr != S_OK)
+	{
+		LogHostError(hr);
+		LogPaError(result = paInvalidDevice);
+		goto error;
+	}
+
+    // Correct buffer to max size if it maxed out result of GetBufferSize
+	stream->in.bufferSize = maxBufferSize;
+
+	// Get interface latency (actually uneeded as we calculate latency from the size
+	// of maxBufferSize).
+    hr = IAudioClient_GetStreamLatency(stream->in.clientParent, &stream->in.deviceLatency);
+    if (hr != S_OK)
+	{
+		LogHostError(hr);
+		LogPaError(result = paInvalidDevice);
+		goto error;
+	}
+	//stream->in.latencySeconds = nano100ToSeconds(stream->in.deviceLatency);
+
+    // Number of frames that are required at each period
+	stream->in.framesPerHostCallback = maxBufferSize;
+
+	// Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
+	stream->in.framesPerBuffer =
+		(stream->in.userBufferAndHostMatch ? stream->in.framesPerHostCallback : framesPerBuffer);
+
+	// Calculate buffer latency
+	buffer_latency = (PaTime)maxBufferSize / stream->in.wavex.Format.nSamplesPerSec;
+
+	// Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
+	stream->in.latencySeconds = buffer_latency;
+
+	PRINT(("WASAPI::OpenStream(input): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->in.framesPerHostCallback, (float)(stream->in.latencySeconds*1000.0f), (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (stream->in.params.wow64_workaround ? "YES" : "NO"), (stream->in.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
+
+	return paNoError;
+
+error:
+
+	return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *streamCallback,
+                           void *userData )
+{
+    PaError result = paNoError;
+	HRESULT hr;
+    PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
+    PaWasapiStream *stream = NULL;
+    int inputChannelCount, outputChannelCount;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+	PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
+	PaWasapiDeviceInfo *info = NULL;
+	ULONG framesPerHostCallback;
+	PaUtilHostBufferSizeMode bufferMode;
+	const BOOL fullDuplex = ((inputParameters != NULL) && (outputParameters != NULL));
+
+	// validate PaStreamParameters
+	if ((result = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
+		return LogPaError(result);
+
+    // Validate platform specific flags
+    if ((streamFlags & paPlatformSpecificFlags) != 0)
+	{
+		LogPaError(result = paInvalidFlag); /* unexpected platform specific flag */
+		goto error;
+	}
+
+	// Allocate memory for PaWasapiStream
+    if ((stream = (PaWasapiStream *)PaUtil_AllocateMemory(sizeof(PaWasapiStream))) == NULL)
+	{
+        LogPaError(result = paInsufficientMemory);
+        goto error;
+    }
+
+	// Default thread priority is Audio: for exclusive mode we will use Pro Audio.
+	stream->nThreadPriority = eThreadPriorityAudio;
+
+	// Set default number of frames: paFramesPerBufferUnspecified
+	if (framesPerBuffer == paFramesPerBufferUnspecified)
+	{
+		UINT32 framesPerBufferIn  = 0, framesPerBufferOut = 0;
+		if (inputParameters != NULL)
+		{
+			info = &paWasapi->devInfo[inputParameters->device];
+			framesPerBufferIn = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
+		}
+		if (outputParameters != NULL)
+		{
+			info = &paWasapi->devInfo[outputParameters->device];
+			framesPerBufferOut = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
+		}
+		// choosing maximum default size
+		framesPerBuffer = max(framesPerBufferIn, framesPerBufferOut);
+	}
+	if (framesPerBuffer == 0)
+		framesPerBuffer = ((UINT32)sampleRate / 100) * 2;
+
+	// Try create device: Input
+	if (inputParameters != NULL)
+    {
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+		inputStreamInfo   = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
+        info              = &paWasapi->devInfo[inputParameters->device];
+		stream->in.flags  = (inputStreamInfo ? inputStreamInfo->flags : 0);
+
+		// Select Exclusive/Shared mode
+		stream->in.shareMode = AUDCLNT_SHAREMODE_SHARED;
+        if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiExclusive))
+		{
+			// Boost thread priority
+			stream->nThreadPriority = eThreadPriorityProAudio;
+			// Make Exclusive
+			stream->in.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
+		}
+
+		// If user provided explicit thread priority level, use it
+        if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiThreadPriority))
+		{
+			if ((inputStreamInfo->threadPriority > eThreadPriorityNone) &&
+				(inputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
+				stream->nThreadPriority = inputStreamInfo->threadPriority;
+		}
+
+		// Choose processing mode
+		stream->in.streamFlags = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
+		if (paWasapi->useWOW64Workaround)
+			stream->in.streamFlags = 0; // polling interface
+		else
+		if (streamCallback == NULL)
+			stream->in.streamFlags = 0; // polling interface
+		else
+		if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiPolling))
+			stream->in.streamFlags = 0; // polling interface
+		else
+		if (fullDuplex)
+			stream->in.streamFlags = 0; // polling interface is implemented for full-duplex mode also
+
+		// Fill parameters for Audio Client creation
+		stream->in.params.device_info       = info;
+		stream->in.params.stream_params     = (*inputParameters);
+		if (inputStreamInfo != NULL)
+		{
+			stream->in.params.wasapi_params = (*inputStreamInfo);
+			stream->in.params.stream_params.hostApiSpecificStreamInfo = &stream->in.params.wasapi_params;
+		}
+		stream->in.params.frames_per_buffer = framesPerBuffer;
+		stream->in.params.sample_rate       = sampleRate;
+		stream->in.params.blocking          = (streamCallback == NULL);
+		stream->in.params.full_duplex       = fullDuplex;
+		stream->in.params.wow64_workaround  = paWasapi->useWOW64Workaround;
+
+		// Create and activate audio client
+		hr = ActivateAudioClientInput(stream);
+        if (hr != S_OK)
+		{
+			LogPaError(result = paInvalidDevice);
+			goto error;
+        }
+
+		// Get closest format
+        hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat( WaveToPaFormat(&stream->in.wavex), inputSampleFormat );
+
+        // Set user-side custom host processor
+        if ((inputStreamInfo != NULL) &&
+            (inputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
+        {
+            stream->hostProcessOverrideInput.processor = inputStreamInfo->hostProcessorInput;
+            stream->hostProcessOverrideInput.userData = userData;
+        }
+
+		// Only get IAudioCaptureClient input once here instead of getting it at multiple places based on the use
+		hr = IAudioClient_GetService(stream->in.clientParent, &pa_IID_IAudioCaptureClient, (void **)&stream->captureClientParent);
+		if (hr != S_OK)
+		{
+			LogHostError(hr);
+			LogPaError(result = paUnanticipatedHostError);
+			goto error;
+		}
+
+		// Create ring buffer for blocking mode (It is needed because we fetch Input packets, not frames,
+		// and thus we have to save partial packet if such remains unread)
+		if (stream->in.params.blocking == TRUE)
+		{
+			UINT32 bufferFrames = ALIGN_NEXT_POW2((stream->in.framesPerHostCallback / WASAPI_PACKETS_PER_INPUT_BUFFER) * 2);
+			UINT32 frameSize    = stream->in.wavex.Format.nBlockAlign;
+
+			// buffer
+			if ((stream->in.tailBuffer = PaUtil_AllocateMemory(sizeof(PaUtilRingBuffer))) == NULL)
+			{
+				LogPaError(result = paInsufficientMemory);
+				goto error;
+			}
+			memset(stream->in.tailBuffer, 0, sizeof(PaUtilRingBuffer));
+
+			// buffer memory region
+			stream->in.tailBufferMemory = PaUtil_AllocateMemory(frameSize * bufferFrames);
+			if (stream->in.tailBufferMemory == NULL)
+			{
+				LogPaError(result = paInsufficientMemory);
+				goto error;
+			}
+
+			// initialize
+			if (PaUtil_InitializeRingBuffer(stream->in.tailBuffer, frameSize, bufferFrames,	stream->in.tailBufferMemory) != 0)
+			{
+				LogPaError(result = paInternalError);
+				goto error;
+			}
+		}
+	}
+    else
+    {
+        inputChannelCount = 0;
+        inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */
+    }
+
+	// Try create device: Output
+    if (outputParameters != NULL)
+    {
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+		outputStreamInfo   = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
+		info               = &paWasapi->devInfo[outputParameters->device];
+		stream->out.flags  = (outputStreamInfo ? outputStreamInfo->flags : 0);
+
+		// Select Exclusive/Shared mode
+		stream->out.shareMode = AUDCLNT_SHAREMODE_SHARED;
+        if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiExclusive))
+		{
+			// Boost thread priority
+			stream->nThreadPriority = eThreadPriorityProAudio;
+			// Make Exclusive
+			stream->out.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
+		}
+
+		// If user provided explicit thread priority level, use it
+        if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiThreadPriority))
+		{
+			if ((outputStreamInfo->threadPriority > eThreadPriorityNone) &&
+				(outputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
+				stream->nThreadPriority = outputStreamInfo->threadPriority;
+		}
+
+		// Choose processing mode
+		stream->out.streamFlags = (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
+		if (paWasapi->useWOW64Workaround)
+			stream->out.streamFlags = 0; // polling interface
+		else
+		if (streamCallback == NULL)
+			stream->out.streamFlags = 0; // polling interface
+		else
+		if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiPolling))
+			stream->out.streamFlags = 0; // polling interface
+		else
+		if (fullDuplex)
+			stream->out.streamFlags = 0; // polling interface is implemented for full-duplex mode also
+
+		// Fill parameters for Audio Client creation
+		stream->out.params.device_info       = info;
+		stream->out.params.stream_params     = (*outputParameters);
+		if (inputStreamInfo != NULL)
+		{
+			stream->out.params.wasapi_params = (*outputStreamInfo);
+			stream->out.params.stream_params.hostApiSpecificStreamInfo = &stream->out.params.wasapi_params;
+		}
+		stream->out.params.frames_per_buffer = framesPerBuffer;
+		stream->out.params.sample_rate       = sampleRate;
+		stream->out.params.blocking          = (streamCallback == NULL);
+		stream->out.params.full_duplex       = fullDuplex;
+		stream->out.params.wow64_workaround  = paWasapi->useWOW64Workaround;
+
+		// Create and activate audio client
+		hr = ActivateAudioClientOutput(stream);
+        if (hr != S_OK)
+		{
+			LogPaError(result = paInvalidDevice);
+			goto error;
+        }
+
+		// Get closest format
+        hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( WaveToPaFormat(&stream->out.wavex), outputSampleFormat );
+
+        // Set user-side custom host processor
+        if ((outputStreamInfo != NULL) &&
+            (outputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
+        {
+            stream->hostProcessOverrideOutput.processor = outputStreamInfo->hostProcessorOutput;
+            stream->hostProcessOverrideOutput.userData = userData;
+        }
+
+		// Only get IAudioCaptureClient output once here instead of getting it at multiple places based on the use
+		hr = IAudioClient_GetService(stream->out.clientParent, &pa_IID_IAudioRenderClient, (void **)&stream->renderClientParent);
+		if (hr != S_OK)
+		{
+			LogHostError(hr);
+			LogPaError(result = paUnanticipatedHostError);
+			goto error;
+		}
+	}
+    else
+    {
+        outputChannelCount = 0;
+        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */
+    }
+
+	// log full-duplex
+	if (fullDuplex)
+		PRINT(("WASAPI::OpenStream: full-duplex mode\n"));
+
+	// paWinWasapiPolling must be on/or not on both streams
+	if ((inputParameters != NULL) && (outputParameters != NULL))
+	{
+		if ((inputStreamInfo != NULL) && (outputStreamInfo != NULL))
+		{
+			if (((inputStreamInfo->flags & paWinWasapiPolling) &&
+				!(outputStreamInfo->flags & paWinWasapiPolling))
+				||
+				(!(inputStreamInfo->flags & paWinWasapiPolling) &&
+				 (outputStreamInfo->flags & paWinWasapiPolling)))
+			{
+				LogPaError(result = paInvalidFlag);
+				goto error;
+			}
+		}
+	}
+
+	// Initialize stream representation
+    if (streamCallback)
+    {
+		stream->bBlocking = FALSE;
+        PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
+                                              &paWasapi->callbackStreamInterface,
+											  streamCallback, userData);
+    }
+    else
+    {
+		stream->bBlocking = TRUE;
+        PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
+                                              &paWasapi->blockingStreamInterface,
+											  streamCallback, userData);
+    }
+
+	// Initialize CPU measurer
+    PaUtil_InitializeCpuLoadMeasurer(&stream->cpuLoadMeasurer, sampleRate);
+
+	if (outputParameters && inputParameters)
+	{
+		// serious problem #1 - No, Not a problem, especially concerning Exclusive mode.
+		// Input device in exclusive mode somehow is getting large buffer always, thus we
+		// adjust Output latency to reflect it, thus period will differ but playback will be
+		// normal.
+		/*if (stream->in.period != stream->out.period)
+		{
+			PRINT(("WASAPI: OpenStream: period discrepancy\n"));
+			LogPaError(result = paBadIODeviceCombination);
+			goto error;
+		}*/
+
+		// serious problem #2 - No, Not a problem, as framesPerHostCallback take into account
+		// sample size while it is not a problem for PA full-duplex, we must care of
+		// preriod only!
+		/*if (stream->out.framesPerHostCallback != stream->in.framesPerHostCallback)
+		{
+			PRINT(("WASAPI: OpenStream: framesPerHostCallback discrepancy\n"));
+			goto error;
+		}*/
+	}
+
+	// Calculate frames per host for processor
+	framesPerHostCallback = (outputParameters ? stream->out.framesPerBuffer : stream->in.framesPerBuffer);
+
+	// Choose correct mode of buffer processing:
+	// Exclusive/Shared non paWinWasapiPolling mode: paUtilFixedHostBufferSize - always fixed
+	// Exclusive/Shared paWinWasapiPolling mode: paUtilBoundedHostBufferSize - may vary for Exclusive or Full-duplex
+	bufferMode = paUtilFixedHostBufferSize;
+	if (inputParameters) // !!! WASAPI IAudioCaptureClient::GetBuffer extracts not number of frames but 1 packet, thus we always must adapt
+		bufferMode = paUtilBoundedHostBufferSize;
+	else
+	if (outputParameters)
+	{
+		if ((stream->out.buffers == 1) &&
+			(!stream->out.streamFlags || ((stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
+			bufferMode = paUtilBoundedHostBufferSize;
+	}
+	stream->bufferMode = bufferMode;
+
+    // Initialize buffer processor
+    result =  PaUtil_InitializeBufferProcessor(
+		&stream->bufferProcessor,
+        inputChannelCount,
+		inputSampleFormat,
+		hostInputSampleFormat,
+        outputChannelCount,
+		outputSampleFormat,
+		hostOutputSampleFormat,
+        sampleRate,
+		streamFlags,
+		framesPerBuffer,
+        framesPerHostCallback,
+		bufferMode,
+        streamCallback,
+		userData);
+    if (result != paNoError)
+	{
+		LogPaError(result);
+        goto error;
+	}
+
+	// Set Input latency
+    stream->streamRepresentation.streamInfo.inputLatency =
+            ((double)PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor) / sampleRate)
+			+ ((inputParameters)?stream->in.latencySeconds : 0);
+
+	// Set Output latency
+    stream->streamRepresentation.streamInfo.outputLatency =
+            ((double)PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor) / sampleRate)
+			+ ((outputParameters)?stream->out.latencySeconds : 0);
+
+	// Set SR
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    (*s) = (PaStream *)stream;
+    return result;
+
+error:
+
+    if (stream != NULL)
+		CloseStream(stream);
+
+    return result;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+	// abort active stream
+	if (IsStreamActive(s))
+	{
+		result = AbortStream(s);
+	}
+
+    SAFE_RELEASE(stream->captureClientParent);
+    SAFE_RELEASE(stream->renderClientParent);
+    SAFE_RELEASE(stream->out.clientParent);
+    SAFE_RELEASE(stream->in.clientParent);
+	SAFE_RELEASE(stream->inVol);
+	SAFE_RELEASE(stream->outVol);
+
+	CloseHandle(stream->event[S_INPUT]);
+	CloseHandle(stream->event[S_OUTPUT]);
+
+	_StreamCleanup(stream);
+
+	PaWasapi_FreeMemory(stream->in.monoBuffer);
+	PaWasapi_FreeMemory(stream->out.monoBuffer);
+
+	PaUtil_FreeMemory(stream->in.tailBuffer);
+	PaUtil_FreeMemory(stream->in.tailBufferMemory);
+
+	PaUtil_FreeMemory(stream->out.tailBuffer);
+	PaUtil_FreeMemory(stream->out.tailBufferMemory);
+
+    PaUtil_TerminateBufferProcessor(&stream->bufferProcessor);
+    PaUtil_TerminateStreamRepresentation(&stream->streamRepresentation);
+    PaUtil_FreeMemory(stream);
+
+    return result;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT UnmarshalSubStreamComPointers(PaWasapiSubStream *substream) 
+{
+	HRESULT hResult = S_OK;
+	HRESULT hFirstBadResult = S_OK;
+	substream->clientProc = NULL;
+
+	// IAudioClient
+	hResult = CoGetInterfaceAndReleaseStream(substream->clientStream, &pa_IID_IAudioClient, (LPVOID*)&substream->clientProc);
+	substream->clientStream = NULL;
+	if (hResult != S_OK) 
+	{
+		hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+	}
+
+	return hFirstBadResult;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT UnmarshalStreamComPointers(PaWasapiStream *stream) 
+{
+	HRESULT hResult = S_OK;
+	HRESULT hFirstBadResult = S_OK;
+	stream->captureClient = NULL;
+	stream->renderClient = NULL;
+	stream->in.clientProc = NULL;
+	stream->out.clientProc = NULL;
+
+	if (NULL != stream->in.clientParent) 
+	{
+		// SubStream pointers
+		hResult = UnmarshalSubStreamComPointers(&stream->in);
+		if (hResult != S_OK) 
+		{
+			hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+		}
+
+		// IAudioCaptureClient
+		hResult = CoGetInterfaceAndReleaseStream(stream->captureClientStream, &pa_IID_IAudioCaptureClient, (LPVOID*)&stream->captureClient);
+		stream->captureClientStream = NULL;
+		if (hResult != S_OK) 
+		{
+			hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+		}
+	}
+
+	if (NULL != stream->out.clientParent) 
+	{
+		// SubStream pointers
+		hResult = UnmarshalSubStreamComPointers(&stream->out);
+		if (hResult != S_OK) 
+		{
+			hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+		}
+
+		// IAudioRenderClient
+		hResult = CoGetInterfaceAndReleaseStream(stream->renderClientStream, &pa_IID_IAudioRenderClient, (LPVOID*)&stream->renderClient);
+		stream->renderClientStream = NULL;
+		if (hResult != S_OK) 
+		{
+			hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
+		}
+	}
+
+	return hFirstBadResult;
+}
+
+// -----------------------------------------------------------------------------------------
+void ReleaseUnmarshaledSubComPointers(PaWasapiSubStream *substream) 
+{
+	SAFE_RELEASE(substream->clientProc);
+}
+
+// -----------------------------------------------------------------------------------------
+void ReleaseUnmarshaledComPointers(PaWasapiStream *stream) 
+{
+	// Release AudioClient services first
+	SAFE_RELEASE(stream->captureClient);
+	SAFE_RELEASE(stream->renderClient);
+
+	// Release AudioClients
+	ReleaseUnmarshaledSubComPointers(&stream->in);
+	ReleaseUnmarshaledSubComPointers(&stream->out);
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT MarshalSubStreamComPointers(PaWasapiSubStream *substream) 
+{
+	HRESULT hResult;
+	substream->clientStream = NULL;
+
+	// IAudioClient
+	hResult = CoMarshalInterThreadInterfaceInStream(&pa_IID_IAudioClient, (LPUNKNOWN)substream->clientParent, &substream->clientStream);
+	if (hResult != S_OK)
+		goto marshal_sub_error;
+
+	return hResult;
+
+	// If marshaling error occurred, make sure to release everything.
+marshal_sub_error:
+
+	UnmarshalSubStreamComPointers(substream);
+	ReleaseUnmarshaledSubComPointers(substream);
+	return hResult;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT MarshalStreamComPointers(PaWasapiStream *stream) 
+{
+	HRESULT hResult = S_OK;
+	stream->captureClientStream = NULL;
+	stream->in.clientStream = NULL;
+	stream->renderClientStream = NULL;
+	stream->out.clientStream = NULL;
+
+	if (NULL != stream->in.clientParent) 
+	{
+		// SubStream pointers
+		hResult = MarshalSubStreamComPointers(&stream->in);
+		if (hResult != S_OK) 
+			goto marshal_error;
+
+		// IAudioCaptureClient
+		hResult = CoMarshalInterThreadInterfaceInStream(&pa_IID_IAudioCaptureClient, (LPUNKNOWN)stream->captureClientParent, &stream->captureClientStream);
+		if (hResult != S_OK) 
+			goto marshal_error;
+	}
+
+	if (NULL != stream->out.clientParent) 
+	{
+		// SubStream pointers
+		hResult = MarshalSubStreamComPointers(&stream->out);
+		if (hResult != S_OK) 
+			goto marshal_error;
+
+		// IAudioRenderClient
+		hResult = CoMarshalInterThreadInterfaceInStream(&pa_IID_IAudioRenderClient, (LPUNKNOWN)stream->renderClientParent, &stream->renderClientStream);
+		if (hResult != S_OK) 
+			goto marshal_error;
+	}
+
+	return hResult;
+
+	// If marshaling error occurred, make sure to release everything.
+marshal_error:
+
+	UnmarshalStreamComPointers(stream);
+	ReleaseUnmarshaledComPointers(stream);
+	return hResult;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError StartStream( PaStream *s )
+{
+	HRESULT hr;
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+	PaError result = paNoError;
+
+	// check if stream is active already
+	if (IsStreamActive(s))
+		return paStreamIsNotStopped;
+
+    PaUtil_ResetBufferProcessor(&stream->bufferProcessor);
+
+	// Cleanup handles (may be necessary if stream was stopped by itself due to error)
+	_StreamCleanup(stream);
+
+	// Create close event
+	if ((stream->hCloseRequest = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL) 
+	{
+		result = paInsufficientMemory;
+		goto start_error;
+	}
+
+	// Create thread
+	if (!stream->bBlocking)
+	{
+		// Create thread events
+		stream->hThreadStart = CreateEvent(NULL, TRUE, FALSE, NULL);
+		stream->hThreadExit  = CreateEvent(NULL, TRUE, FALSE, NULL);
+		if ((stream->hThreadStart == NULL) || (stream->hThreadExit == NULL))
+		{
+			result = paInsufficientMemory;
+			goto start_error;
+		}
+
+		// Marshal WASAPI interface pointers for safe use in thread created below.
+		if ((hr = MarshalStreamComPointers(stream)) != S_OK) 
+		{
+			PRINT(("Failed marshaling stream COM pointers."));
+			result = paUnanticipatedHostError;
+			goto nonblocking_start_error;
+		}
+
+		if ((stream->in.clientParent  && (stream->in.streamFlags  & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)) ||
+			(stream->out.clientParent && (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)))
+		{
+			if ((stream->hThread = CREATE_THREAD(ProcThreadEvent)) == NULL) 
+			{
+				PRINT(("Failed creating thread: ProcThreadEvent."));
+				result = paUnanticipatedHostError;
+				goto nonblocking_start_error;
+			}
+		}
+		else
+		{
+			if ((stream->hThread = CREATE_THREAD(ProcThreadPoll)) == NULL) 
+			{
+				PRINT(("Failed creating thread: ProcThreadPoll."));
+				result = paUnanticipatedHostError;
+				goto nonblocking_start_error;
+			}
+		}
+
+		// Wait for thread to start
+		if (WaitForSingleObject(stream->hThreadStart, 60*1000) == WAIT_TIMEOUT) 
+		{
+			PRINT(("Failed starting thread: timeout."));
+			result = paUnanticipatedHostError;
+			goto nonblocking_start_error;
+		}
+	}
+	else
+	{
+		// Create blocking operation events (non-signaled event means - blocking operation is pending)
+		if (stream->out.clientParent != NULL) 
+		{
+			if ((stream->hBlockingOpStreamWR = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) 
+			{
+				result = paInsufficientMemory;
+				goto start_error;
+			}
+		}
+		if (stream->in.clientParent != NULL) 
+		{
+			if ((stream->hBlockingOpStreamRD = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) 
+			{
+				result = paInsufficientMemory;
+				goto start_error;
+			}
+		}
+
+		// Initialize event & start INPUT stream
+		if (stream->in.clientParent != NULL)
+		{
+			if ((hr = IAudioClient_Start(stream->in.clientParent)) != S_OK)
+			{
+				LogHostError(hr);
+				result = paUnanticipatedHostError;
+				goto start_error;
+			}
+		}
+
+		// Initialize event & start OUTPUT stream
+		if (stream->out.clientParent != NULL)
+		{
+			// Start
+			if ((hr = IAudioClient_Start(stream->out.clientParent)) != S_OK)
+			{
+				LogHostError(hr);
+				result = paUnanticipatedHostError;
+				goto start_error;
+			}
+		}
+
+		// Set parent to working pointers to use shared functions.
+		stream->captureClient  = stream->captureClientParent;
+		stream->renderClient   = stream->renderClientParent;
+		stream->in.clientProc  = stream->in.clientParent;
+		stream->out.clientProc = stream->out.clientParent;
+
+		// Signal: stream running.
+		stream->running = TRUE;
+	}
+
+    return result;
+
+nonblocking_start_error:
+
+	// Set hThreadExit event to prevent blocking during cleanup
+	SetEvent(stream->hThreadExit);
+	UnmarshalStreamComPointers(stream);
+	ReleaseUnmarshaledComPointers(stream);
+
+start_error:
+
+	StopStream(s);
+	return result;
+}
+
+// ------------------------------------------------------------------------------------------
+void _StreamFinish(PaWasapiStream *stream)
+{
+	// Issue command to thread to stop processing and wait for thread exit
+	if (!stream->bBlocking)
+	{
+		SignalObjectAndWait(stream->hCloseRequest, stream->hThreadExit, INFINITE, FALSE);
+	}
+	else
+	// Blocking mode does not own thread
+	{
+		// Signal close event and wait for each of 2 blocking operations to complete
+		if (stream->out.clientParent)
+			SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamWR, INFINITE, TRUE);
+		if (stream->out.clientParent)
+			SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamRD, INFINITE, TRUE);
+
+		// Process stop
+		_StreamOnStop(stream);
+	}
+
+	// Cleanup handles
+	_StreamCleanup(stream);
+
+    stream->running = FALSE;
+}
+
+// ------------------------------------------------------------------------------------------
+void _StreamCleanup(PaWasapiStream *stream)
+{
+	// Close thread handles to allow restart
+	SAFE_CLOSE(stream->hThread);
+	SAFE_CLOSE(stream->hThreadStart);
+	SAFE_CLOSE(stream->hThreadExit);
+	SAFE_CLOSE(stream->hCloseRequest);
+	SAFE_CLOSE(stream->hBlockingOpStreamRD);
+	SAFE_CLOSE(stream->hBlockingOpStreamWR);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError StopStream( PaStream *s )
+{
+	// Finish stream
+	_StreamFinish((PaWasapiStream *)s);
+    return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError AbortStream( PaStream *s )
+{
+	// Finish stream
+	_StreamFinish((PaWasapiStream *)s);
+    return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsStreamStopped( PaStream *s )
+{
+	return !((PaWasapiStream *)s)->running;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError IsStreamActive( PaStream *s )
+{
+    return ((PaWasapiStream *)s)->running;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaTime GetStreamTime( PaStream *s )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+    /* suppress unused variable warnings */
+    (void) stream;
+
+    return PaUtil_GetTime();
+}
+
+// ------------------------------------------------------------------------------------------
+static double GetStreamCpuLoad( PaStream* s )
+{
+	return PaUtil_GetCpuLoad(&((PaWasapiStream *)s)->cpuLoadMeasurer);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError ReadStream( PaStream* s, void *_buffer, unsigned long frames )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+	HRESULT hr = S_OK;
+	BYTE *user_buffer = (BYTE *)_buffer;
+	BYTE *wasapi_buffer = NULL;
+	DWORD flags = 0;
+	UINT32 i, available, sleep = 0;
+	unsigned long processed;
+	ThreadIdleScheduler sched;
+
+	// validate
+	if (!stream->running)
+		return paStreamIsStopped;
+	if (stream->captureClient == NULL)
+		return paBadStreamPtr;
+
+	// Notify blocking op has begun
+	ResetEvent(stream->hBlockingOpStreamRD);
+
+	// Use thread scheduling for 500 microseconds (emulated) when wait time for frames is less than
+	// 1 milliseconds, emulation helps to normalize CPU consumption and avoids too busy waiting
+	ThreadIdleScheduler_Setup(&sched, 1, 250/* microseconds */);
+
+    // Make a local copy of the user buffer pointer(s), this is necessary
+	// because PaUtil_CopyOutput() advances these pointers every time it is called
+    if (!stream->bufferProcessor.userInputIsInterleaved)
+    {
+		user_buffer = (BYTE *)alloca(sizeof(BYTE *) * stream->bufferProcessor.inputChannelCount);
+        if (user_buffer == NULL)
+            return paInsufficientMemory;
+
+        for (i = 0; i < stream->bufferProcessor.inputChannelCount; ++i)
+            ((BYTE **)user_buffer)[i] = ((BYTE **)_buffer)[i];
+    }
+
+	// Findout if there are tail frames, flush them all before reading hardware
+	if ((available = PaUtil_GetRingBufferReadAvailable(stream->in.tailBuffer)) != 0)
+	{
+		ring_buffer_size_t buf1_size = 0, buf2_size = 0, read, desired;
+		void *buf1 = NULL, *buf2 = NULL;
+
+		// Limit desired to amount of requested frames
+		desired = available;
+		if ((UINT32)desired > frames)
+			desired = frames;
+		
+		// Get pointers to read regions
+		read = PaUtil_GetRingBufferReadRegions(stream->in.tailBuffer, desired, &buf1, &buf1_size, &buf2, &buf2_size);
+
+		if (buf1 != NULL)
+		{
+			// Register available frames to processor
+			PaUtil_SetInputFrameCount(&stream->bufferProcessor, buf1_size);
+
+			// Register host buffer pointer to processor
+			PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, buf1, stream->bufferProcessor.inputChannelCount);
+
+			// Copy user data to host buffer (with conversion if applicable)
+			processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, buf1_size);
+			frames -= processed;
+		}
+
+		if (buf2 != NULL)
+		{
+			// Register available frames to processor
+			PaUtil_SetInputFrameCount(&stream->bufferProcessor, buf2_size);
+
+			// Register host buffer pointer to processor
+			PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, buf2, stream->bufferProcessor.inputChannelCount);
+
+			// Copy user data to host buffer (with conversion if applicable)
+			processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, buf2_size);
+			frames -= processed;
+		}
+
+		// Advance
+		PaUtil_AdvanceRingBufferReadIndex(stream->in.tailBuffer, read);
+	}
+
+	// Read hardware
+	while (frames != 0)
+	{
+		// Check if blocking call must be interrupted
+		if (WaitForSingleObject(stream->hCloseRequest, sleep) != WAIT_TIMEOUT)
+			break;
+
+		// Get available frames (must be finding out available frames before call to IAudioCaptureClient_GetBuffer
+		// othervise audio glitches will occur inExclusive mode as it seems that WASAPI has some scheduling/
+		// processing problems when such busy polling with IAudioCaptureClient_GetBuffer occurs)
+		if ((hr = _PollGetInputFramesAvailable(stream, &available)) != S_OK)
+		{
+			LogHostError(hr);
+			return paUnanticipatedHostError;
+		}
+
+		// Wait for more frames to become available
+		if (available == 0)
+		{
+			// Exclusive mode may require latency of 1 millisecond, thus we shall sleep
+			// around 500 microseconds (emulated) to collect packets in time
+			if (stream->in.shareMode != AUDCLNT_SHAREMODE_EXCLUSIVE)
+			{
+				UINT32 sleep_frames = (frames < stream->in.framesPerHostCallback ? frames : stream->in.framesPerHostCallback);
+
+				sleep  = GetFramesSleepTime(sleep_frames, stream->in.wavex.Format.nSamplesPerSec);
+				sleep /= 4; // wait only for 1/4 of the buffer
+
+				// WASAPI input provides packets, thus expiring packet will result in bad audio
+				// limit waiting time to 2 seconds (will always work for smallest buffer in Shared)
+				if (sleep > 2)
+					sleep = 2;
+
+				// Avoid busy waiting, schedule next 1 millesecond wait
+				if (sleep == 0)
+					sleep = ThreadIdleScheduler_NextSleep(&sched);
+			}
+			else
+			{
+				if ((sleep = ThreadIdleScheduler_NextSleep(&sched)) != 0)
+				{
+					Sleep(sleep);
+					sleep = 0;
+				}
+			}
+
+			continue;
+		}
+
+		// Get the available data in the shared buffer.
+		if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &wasapi_buffer, &available, &flags, NULL, NULL)) != S_OK)
+		{
+			// Buffer size is too small, waiting
+			if (hr != AUDCLNT_S_BUFFER_EMPTY)
+			{
+				LogHostError(hr);
+				goto end;
+			}
+
+			continue;
+		}
+
+		// Register available frames to processor
+        PaUtil_SetInputFrameCount(&stream->bufferProcessor, available);
+
+		// Register host buffer pointer to processor
+        PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, wasapi_buffer, stream->bufferProcessor.inputChannelCount);
+
+		// Copy user data to host buffer (with conversion if applicable)
+		processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, frames);
+		frames -= processed;
+
+		// Save tail into buffer
+		if ((frames == 0) && (available > processed))
+		{
+			UINT32 bytes_processed = processed * stream->in.wavex.Format.nBlockAlign;
+			UINT32 frames_to_save  = available - processed;
+
+			PaUtil_WriteRingBuffer(stream->in.tailBuffer, wasapi_buffer + bytes_processed, frames_to_save);
+		}
+
+		// Release host buffer
+		if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, available)) != S_OK)
+		{
+			LogHostError(hr);
+			goto end;
+		}
+	}
+
+end:
+
+	// Notify blocking op has ended
+	SetEvent(stream->hBlockingOpStreamRD);
+
+	return (hr != S_OK ? paUnanticipatedHostError : paNoError);
+}
+
+// ------------------------------------------------------------------------------------------
+static PaError WriteStream( PaStream* s, const void *_buffer, unsigned long frames )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+	//UINT32 frames;
+	const BYTE *user_buffer = (const BYTE *)_buffer;
+	BYTE *wasapi_buffer;
+	HRESULT hr = S_OK;
+	UINT32 i, available, sleep = 0;
+	unsigned long processed;
+	ThreadIdleScheduler sched;
+
+	// validate
+	if (!stream->running)
+		return paStreamIsStopped;
+	if (stream->renderClient == NULL)
+		return paBadStreamPtr;
+
+	// Notify blocking op has begun
+	ResetEvent(stream->hBlockingOpStreamWR);
+
+	// Use thread scheduling for 500 microseconds (emulated) when wait time for frames is less than
+	// 1 milliseconds, emulation helps to normalize CPU consumption and avoids too busy waiting
+	ThreadIdleScheduler_Setup(&sched, 1, 500/* microseconds */);
+
+    // Make a local copy of the user buffer pointer(s), this is necessary
+	// because PaUtil_CopyOutput() advances these pointers every time it is called
+    if (!stream->bufferProcessor.userOutputIsInterleaved)
+    {
+        user_buffer = (const BYTE *)alloca(sizeof(const BYTE *) * stream->bufferProcessor.outputChannelCount);
+        if (user_buffer == NULL)
+            return paInsufficientMemory;
+
+        for (i = 0; i < stream->bufferProcessor.outputChannelCount; ++i)
+            ((const BYTE **)user_buffer)[i] = ((const BYTE **)_buffer)[i];
+    }
+
+	// Blocking (potentially, untill 'frames' are consumed) loop
+	while (frames != 0)
+	{
+		// Check if blocking call must be interrupted
+		if (WaitForSingleObject(stream->hCloseRequest, sleep) != WAIT_TIMEOUT)
+			break;
+
+		// Get frames available
+		if ((hr = _PollGetOutputFramesAvailable(stream, &available)) != S_OK)
+		{
+			LogHostError(hr);
+			goto end;
+		}
+
+		// Wait for more frames to become available
+		if (available == 0)
+		{
+			UINT32 sleep_frames = (frames < stream->out.framesPerHostCallback ? frames : stream->out.framesPerHostCallback);
+
+			sleep  = GetFramesSleepTime(sleep_frames, stream->out.wavex.Format.nSamplesPerSec);
+			sleep /= 2; // wait only for half of the buffer
+
+			// Avoid busy waiting, schedule next 1 millesecond wait
+			if (sleep == 0)
+				sleep = ThreadIdleScheduler_NextSleep(&sched);
+
+			continue;
+		}
+
+		// Keep in 'frmaes' range
+		if (available > frames)
+			available = frames;
+
+		// Get pointer to host buffer
+		if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, available, &wasapi_buffer)) != S_OK)
+		{
+			// Buffer size is too big, waiting
+			if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
+				continue;
+
+			LogHostError(hr);
+			goto end;
+		}
+
+		// Keep waiting again (on Vista it was noticed that WASAPI could SOMETIMES return NULL pointer 
+		// to buffer without returning AUDCLNT_E_BUFFER_TOO_LARGE instead)
+		if (wasapi_buffer == NULL)
+			continue;
+
+		// Register available frames to processor
+        PaUtil_SetOutputFrameCount(&stream->bufferProcessor, available);
+
+		// Register host buffer pointer to processor
+        PaUtil_SetInterleavedOutputChannels(&stream->bufferProcessor, 0, wasapi_buffer,	stream->bufferProcessor.outputChannelCount);
+
+		// Copy user data to host buffer (with conversion if applicable), this call will advance
+		// pointer 'user_buffer' to consumed portion of data
+		processed = PaUtil_CopyOutput(&stream->bufferProcessor, (const void **)&user_buffer, frames);
+		frames -= processed;
+
+		// Release host buffer
+		if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, available, 0)) != S_OK)
+		{
+			LogHostError(hr);
+			goto end;
+		}
+	}
+
+end:
+
+	// Notify blocking op has ended
+	SetEvent(stream->hBlockingOpStreamWR);
+
+	return (hr != S_OK ? paUnanticipatedHostError : paNoError);
+}
+
+unsigned long PaUtil_GetOutputFrameCount( PaUtilBufferProcessor* bp )
+{
+	return bp->hostOutputFrameCount[0];
+}
+
+// ------------------------------------------------------------------------------------------
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+
+	HRESULT hr;
+	UINT32  available = 0;
+
+	// validate
+	if (!stream->running)
+		return paStreamIsStopped;
+	if (stream->captureClient == NULL)
+		return paBadStreamPtr;
+
+	// available in hardware buffer
+	if ((hr = _PollGetInputFramesAvailable(stream, &available)) != S_OK)
+	{
+		LogHostError(hr);
+		return paUnanticipatedHostError;
+	}
+
+	// available in software tail buffer
+	available += PaUtil_GetRingBufferReadAvailable(stream->in.tailBuffer);
+
+    return available;
+}
+
+// ------------------------------------------------------------------------------------------
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)s;
+	HRESULT hr;
+	UINT32  available = 0;
+
+	// validate
+	if (!stream->running)
+		return paStreamIsStopped;
+	if (stream->renderClient == NULL)
+		return paBadStreamPtr;
+
+	if ((hr = _PollGetOutputFramesAvailable(stream, &available)) != S_OK)
+	{
+		LogHostError(hr);
+		return paUnanticipatedHostError;
+	}
+
+	return (signed long)available;
+}
+
+
+// ------------------------------------------------------------------------------------------
+static void WaspiHostProcessingLoop( void *inputBuffer,  long inputFrames,
+                                     void *outputBuffer, long outputFrames,
+                                     void *userData )
+{
+    PaWasapiStream *stream = (PaWasapiStream*)userData;
+    PaStreamCallbackTimeInfo timeInfo = {0,0,0};
+	PaStreamCallbackFlags flags = 0;
+    int callbackResult;
+    unsigned long framesProcessed;
+	HRESULT hr;
+	UINT32 pending;
+
+    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+    /*
+		Pa_GetStreamTime:
+            - generate timing information
+            - handle buffer slips
+    */
+	timeInfo.currentTime = PaUtil_GetTime();
+	// Query input latency
+	if (stream->in.clientProc != NULL)
+	{
+		PaTime pending_time;
+		if ((hr = IAudioClient_GetCurrentPadding(stream->in.clientProc, &pending)) == S_OK)
+			pending_time = (PaTime)pending / (PaTime)stream->in.wavex.Format.nSamplesPerSec;
+		else
+			pending_time = (PaTime)stream->in.latencySeconds;
+
+		timeInfo.inputBufferAdcTime = timeInfo.currentTime + pending_time;
+	}
+	// Query output current latency
+	if (stream->out.clientProc != NULL)
+	{
+		PaTime pending_time;
+		if ((hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &pending)) == S_OK)
+			pending_time = (PaTime)pending / (PaTime)stream->out.wavex.Format.nSamplesPerSec;
+		else
+			pending_time = (PaTime)stream->out.latencySeconds;
+
+		timeInfo.outputBufferDacTime = timeInfo.currentTime + pending_time;
+	}
+
+    /*
+        If you need to byte swap or shift inputBuffer to convert it into a
+        portaudio format, do it here.
+    */
+
+    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, flags );
+
+    /*
+        depending on whether the host buffers are interleaved, non-interleaved
+        or a mixture, you will want to call PaUtil_SetInterleaved*Channels(),
+        PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here.
+    */
+
+    if (stream->bufferProcessor.inputChannelCount > 0)
+    {
+        PaUtil_SetInputFrameCount( &stream->bufferProcessor, inputFrames );
+        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor,
+            0, /* first channel of inputBuffer is channel 0 */
+            inputBuffer,
+            0 ); /* 0 - use inputChannelCount passed to init buffer processor */
+    }
+
+    if (stream->bufferProcessor.outputChannelCount > 0)
+    {
+        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, outputFrames);
+        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor,
+            0, /* first channel of outputBuffer is channel 0 */
+            outputBuffer,
+            0 ); /* 0 - use outputChannelCount passed to init buffer processor */
+    }
+
+    /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing()
+        in general you would pass paContinue for normal operation, and
+        paComplete to drain the buffer processor's internal output buffer.
+        You can check whether the buffer processor's output buffer is empty
+        using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor )
+    */
+    callbackResult = paContinue;
+    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+
+    /*
+        If you need to byte swap or shift outputBuffer to convert it to
+        host format, do it here.
+    */
+
+	PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+    if (callbackResult == paContinue)
+    {
+        /* nothing special to do */
+    }
+    else
+	if (callbackResult == paAbort)
+    {
+		// stop stream
+        SetEvent(stream->hCloseRequest);
+    }
+    else
+    {
+		// stop stream
+        SetEvent(stream->hCloseRequest);
+    }
+}
+
+// ------------------------------------------------------------------------------------------
+HANDLE MMCSS_activate(const char *name)
+{
+    DWORD task_idx = 0;
+    HANDLE hTask = pAvSetMmThreadCharacteristics(name, &task_idx);
+    if (hTask == NULL)
+	{
+        PRINT(("WASAPI: AvSetMmThreadCharacteristics failed!\n"));
+    }
+
+    /*BOOL priority_ok = pAvSetMmThreadPriority(hTask, AVRT_PRIORITY_NORMAL);
+    if (priority_ok == FALSE)
+	{
+        PRINT(("WASAPI: AvSetMmThreadPriority failed!\n"));
+    }*/
+
+	// debug
+    {
+        int    cur_priority		  = GetThreadPriority(GetCurrentThread());
+        DWORD  cur_priority_class = GetPriorityClass(GetCurrentProcess());
+		PRINT(("WASAPI: thread[ priority-0x%X class-0x%X ]\n", cur_priority, cur_priority_class));
+    }
+
+	return hTask;
+}
+
+// ------------------------------------------------------------------------------------------
+void MMCSS_deactivate(HANDLE hTask)
+{
+	if (!hTask)
+		return;
+
+	if (pAvRevertMmThreadCharacteristics(hTask) == FALSE)
+	{
+        PRINT(("WASAPI: AvRevertMmThreadCharacteristics failed!\n"));
+    }
+}
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_ThreadPriorityBoost(void **hTask, PaWasapiThreadPriority nPriorityClass)
+{
+	static const char *mmcs_name[] =
+	{
+		NULL,
+		"Audio",
+		"Capture",
+		"Distribution",
+		"Games",
+		"Playback",
+		"Pro Audio",
+		"Window Manager"
+	};
+	HANDLE task;
+
+	if (hTask == NULL)
+		return paUnanticipatedHostError;
+
+	if ((UINT32)nPriorityClass >= STATIC_ARRAY_SIZE(mmcs_name))
+		return paUnanticipatedHostError;
+
+	task = MMCSS_activate(mmcs_name[nPriorityClass]);
+	if (task == NULL)
+		return paUnanticipatedHostError;
+
+	(*hTask) = task;
+	return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+PaError PaWasapi_ThreadPriorityRevert(void *hTask)
+{
+	if (hTask == NULL)
+		return paUnanticipatedHostError;
+
+	MMCSS_deactivate((HANDLE)hTask);
+
+	return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+// Described at:
+// http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
+
+PaError PaWasapi_GetJackCount(PaDeviceIndex nDevice, int *jcount)
+{
+	PaError ret;
+	HRESULT hr = S_OK;
+	PaDeviceIndex index;
+    IDeviceTopology *pDeviceTopology = NULL;
+    IConnector *pConnFrom = NULL;
+    IConnector *pConnTo = NULL;
+    IPart *pPart = NULL;
+    IKsJackDescription *pJackDesc = NULL;
+	UINT jackCount = 0;
+
+	PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
+	if (paWasapi == NULL)
+		return paNotInitialized;
+
+	// Get device index.
+	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+	// Validate index.
+	if ((UINT32)index >= paWasapi->deviceCount)
+		return paInvalidDevice;
+
+	// Get the endpoint device's IDeviceTopology interface.
+	hr = IMMDevice_Activate(paWasapi->devInfo[index].device, &pa_IID_IDeviceTopology,
+		CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
+	IF_FAILED_JUMP(hr, error);
+
+    // The device topology for an endpoint device always contains just one connector (connector number 0).
+	hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
+	IF_FAILED_JUMP(hr, error);
+
+    // Step across the connection to the jack on the adapter.
+	hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
+    if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
+    {
+        // The adapter device is not currently active.
+        hr = E_NOINTERFACE;
+    }
+	IF_FAILED_JUMP(hr, error);
+
+	// Get the connector's IPart interface.
+	hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
+	IF_FAILED_JUMP(hr, error);
+
+	// Activate the connector's IKsJackDescription interface.
+	hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
+	IF_FAILED_JUMP(hr, error);
+
+	// Return jack count for this device.
+	hr = IKsJackDescription_GetJackCount(pJackDesc, &jackCount);
+	IF_FAILED_JUMP(hr, error);
+
+	// Set.
+	(*jcount) = jackCount;
+
+	// Ok.
+	ret = paNoError;
+
+error:
+
+	SAFE_RELEASE(pDeviceTopology);
+	SAFE_RELEASE(pConnFrom);
+	SAFE_RELEASE(pConnTo);
+	SAFE_RELEASE(pPart);
+	SAFE_RELEASE(pJackDesc);
+
+	LogHostError(hr);
+	return paNoError;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaWasapiJackConnectionType ConvertJackConnectionTypeWASAPIToPA(int connType)
+{
+	switch (connType)
+	{
+		case eConnTypeUnknown:			return eJackConnTypeUnknown;
+#ifdef _KS_
+		case eConnType3Point5mm:		return eJackConnType3Point5mm;
+#else
+		case eConnTypeEighth:		    return eJackConnType3Point5mm;
+#endif
+		case eConnTypeQuarter:			return eJackConnTypeQuarter;
+		case eConnTypeAtapiInternal:	return eJackConnTypeAtapiInternal;
+		case eConnTypeRCA:				return eJackConnTypeRCA;
+		case eConnTypeOptical:			return eJackConnTypeOptical;
+		case eConnTypeOtherDigital:		return eJackConnTypeOtherDigital;
+		case eConnTypeOtherAnalog:		return eJackConnTypeOtherAnalog;
+		case eConnTypeMultichannelAnalogDIN: return eJackConnTypeMultichannelAnalogDIN;
+		case eConnTypeXlrProfessional:	return eJackConnTypeXlrProfessional;
+		case eConnTypeRJ11Modem:		return eJackConnTypeRJ11Modem;
+		case eConnTypeCombination:		return eJackConnTypeCombination;
+	}
+	return eJackConnTypeUnknown;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaWasapiJackGeoLocation ConvertJackGeoLocationWASAPIToPA(int geoLoc)
+{
+	switch (geoLoc)
+	{
+	case eGeoLocRear:				return eJackGeoLocRear;
+	case eGeoLocFront:				return eJackGeoLocFront;
+	case eGeoLocLeft:				return eJackGeoLocLeft;
+	case eGeoLocRight:				return eJackGeoLocRight;
+	case eGeoLocTop:				return eJackGeoLocTop;
+	case eGeoLocBottom:				return eJackGeoLocBottom;
+#ifdef _KS_
+	case eGeoLocRearPanel:			return eJackGeoLocRearPanel;
+#else
+	case eGeoLocRearOPanel:         return eJackGeoLocRearPanel;
+#endif
+	case eGeoLocRiser:				return eJackGeoLocRiser;
+	case eGeoLocInsideMobileLid:	return eJackGeoLocInsideMobileLid;
+	case eGeoLocDrivebay:			return eJackGeoLocDrivebay;
+	case eGeoLocHDMI:				return eJackGeoLocHDMI;
+	case eGeoLocOutsideMobileLid:	return eJackGeoLocOutsideMobileLid;
+	case eGeoLocATAPI:				return eJackGeoLocATAPI;
+	}
+	return eJackGeoLocUnk;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaWasapiJackGenLocation ConvertJackGenLocationWASAPIToPA(int genLoc)
+{
+	switch (genLoc)
+	{
+	case eGenLocPrimaryBox:	return eJackGenLocPrimaryBox;
+	case eGenLocInternal:	return eJackGenLocInternal;
+#ifdef _KS_
+	case eGenLocSeparate:	return eJackGenLocSeparate;
+#else
+	case eGenLocSeperate:	return eJackGenLocSeparate;
+#endif
+	case eGenLocOther:		return eJackGenLocOther;
+	}
+	return eJackGenLocPrimaryBox;
+}
+
+// ------------------------------------------------------------------------------------------
+static PaWasapiJackPortConnection ConvertJackPortConnectionWASAPIToPA(int portConn)
+{
+	switch (portConn)
+	{
+	case ePortConnJack:					return eJackPortConnJack;
+	case ePortConnIntegratedDevice:		return eJackPortConnIntegratedDevice;
+	case ePortConnBothIntegratedAndJack:return eJackPortConnBothIntegratedAndJack;
+	case ePortConnUnknown:				return eJackPortConnUnknown;
+	}
+	return eJackPortConnJack;
+}
+
+// ------------------------------------------------------------------------------------------
+// Described at:
+// http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
+
+PaError PaWasapi_GetJackDescription(PaDeviceIndex nDevice, int jindex, PaWasapiJackDescription *pJackDescription)
+{
+	PaError ret;
+	HRESULT hr = S_OK;
+	PaDeviceIndex index;
+    IDeviceTopology *pDeviceTopology = NULL;
+    IConnector *pConnFrom = NULL;
+    IConnector *pConnTo = NULL;
+    IPart *pPart = NULL;
+    IKsJackDescription *pJackDesc = NULL;
+	KSJACK_DESCRIPTION jack = { 0 };
+
+	PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
+	if (paWasapi == NULL)
+		return paNotInitialized;
+
+	// Get device index.
+	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
+    if (ret != paNoError)
+        return ret;
+
+	// Validate index.
+	if ((UINT32)index >= paWasapi->deviceCount)
+		return paInvalidDevice;
+
+	// Get the endpoint device's IDeviceTopology interface.
+	hr = IMMDevice_Activate(paWasapi->devInfo[index].device, &pa_IID_IDeviceTopology,
+		CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
+	IF_FAILED_JUMP(hr, error);
+
+    // The device topology for an endpoint device always contains just one connector (connector number 0).
+	hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
+	IF_FAILED_JUMP(hr, error);
+
+    // Step across the connection to the jack on the adapter.
+	hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
+    if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
+    {
+        // The adapter device is not currently active.
+        hr = E_NOINTERFACE;
+    }
+	IF_FAILED_JUMP(hr, error);
+
+	// Get the connector's IPart interface.
+	hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
+	IF_FAILED_JUMP(hr, error);
+
+	// Activate the connector's IKsJackDescription interface.
+	hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
+	IF_FAILED_JUMP(hr, error);
+
+	// Test to return jack description struct for index 0.
+	hr = IKsJackDescription_GetJackDescription(pJackDesc, jindex, &jack);
+	IF_FAILED_JUMP(hr, error);
+
+	// Convert WASAPI values to PA format.
+	pJackDescription->channelMapping = jack.ChannelMapping;
+	pJackDescription->color          = jack.Color;
+	pJackDescription->connectionType = ConvertJackConnectionTypeWASAPIToPA(jack.ConnectionType);
+	pJackDescription->genLocation    = ConvertJackGenLocationWASAPIToPA(jack.GenLocation);
+	pJackDescription->geoLocation    = ConvertJackGeoLocationWASAPIToPA(jack.GeoLocation);
+	pJackDescription->isConnected    = jack.IsConnected;
+	pJackDescription->portConnection = ConvertJackPortConnectionWASAPIToPA(jack.PortConnection);
+
+	// Ok.
+	ret = paNoError;
+
+error:
+
+	SAFE_RELEASE(pDeviceTopology);
+	SAFE_RELEASE(pConnFrom);
+	SAFE_RELEASE(pConnTo);
+	SAFE_RELEASE(pPart);
+	SAFE_RELEASE(pJackDesc);
+
+	LogHostError(hr);
+	return ret;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT _PollGetOutputFramesAvailable(PaWasapiStream *stream, UINT32 *available)
+{
+	HRESULT hr;
+	UINT32 frames  = stream->out.framesPerHostCallback,
+		   padding = 0;
+
+	(*available) = 0;
+
+	// get read position
+	if ((hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &padding)) != S_OK)
+		return LogHostError(hr);
+
+	// get available
+	frames -= padding;
+
+	// set
+	(*available) = frames;
+	return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT _PollGetInputFramesAvailable(PaWasapiStream *stream, UINT32 *available)
+{
+	HRESULT hr;
+
+	(*available) = 0;
+
+	// GetCurrentPadding() has opposite meaning to Output stream 
+	if ((hr = IAudioClient_GetCurrentPadding(stream->in.clientProc, available)) != S_OK)
+		return LogHostError(hr);
+
+	return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT ProcessOutputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor, UINT32 frames)
+{
+	HRESULT hr;
+	BYTE *data = NULL;
+
+	// Get buffer
+	if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, frames, &data)) != S_OK)
+	{
+		if (stream->out.shareMode == AUDCLNT_SHAREMODE_SHARED)
+		{
+			// Using GetCurrentPadding to overcome AUDCLNT_E_BUFFER_TOO_LARGE in
+			// shared mode results in no sound in Event-driven mode (MSDN does not
+			// document this, or is it WASAPI bug?), thus we better
+			// try to acquire buffer next time when GetBuffer allows to do so.
+#if 0
+			// Get Read position
+			UINT32 padding = 0;
+			hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &padding);
+			if (hr != S_OK)
+				return LogHostError(hr);
+
+			// Get frames to write
+			frames -= padding;
+			if (frames == 0)
+				return S_OK;
+
+			if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, frames, &data)) != S_OK)
+				return LogHostError(hr);
+#else
+			if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
+				return S_OK; // be silent in shared mode, try again next time
+#endif
+		}
+		else
+			return LogHostError(hr);
+	}
+
+	// Process data
+	if (stream->out.monoMixer != NULL)
+	{
+		// expand buffer
+		UINT32 mono_frames_size = frames * (stream->out.wavex.Format.wBitsPerSample / 8);
+		if (mono_frames_size > stream->out.monoBufferSize)
+			stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
+
+		// process
+		processor[S_OUTPUT].processor(NULL, 0, (BYTE *)stream->out.monoBuffer, frames, processor[S_OUTPUT].userData);
+
+		// mix 1 to 2 channels
+		stream->out.monoMixer(data, stream->out.monoBuffer, frames);
+	}
+	else
+	{
+		processor[S_OUTPUT].processor(NULL, 0, data, frames, processor[S_OUTPUT].userData);
+	}
+
+	// Release buffer
+	if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, frames, 0)) != S_OK)
+		LogHostError(hr);
+
+	return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+HRESULT ProcessInputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor)
+{
+	HRESULT hr = S_OK;
+	UINT32 frames;
+	BYTE *data = NULL;
+	DWORD flags = 0;
+
+	for (;;)
+	{
+		// Check if blocking call must be interrupted
+		if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
+			break;
+
+		// Findout if any frames available
+		frames = 0;
+		if ((hr = _PollGetInputFramesAvailable(stream, &frames)) != S_OK)
+			return hr;
+
+		// Empty/consumed buffer
+		if (frames == 0)
+			break;
+
+		// Get the available data in the shared buffer.
+		if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &data, &frames, &flags, NULL, NULL)) != S_OK)
+		{
+			if (hr == AUDCLNT_S_BUFFER_EMPTY)
+			{
+				hr = S_OK;
+				break; // Empty/consumed buffer
+			}
+
+			return LogHostError(hr);
+			break;
+		}
+
+		// Detect silence
+		// if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
+		//	data = NULL;
+
+		// Process data
+		if (stream->in.monoMixer != NULL)
+		{
+			// expand buffer
+			UINT32 mono_frames_size = frames * (stream->in.wavex.Format.wBitsPerSample / 8);
+			if (mono_frames_size > stream->in.monoBufferSize)
+				stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
+
+			// mix 1 to 2 channels
+			stream->in.monoMixer(stream->in.monoBuffer, data, frames);
+
+			// process
+			processor[S_INPUT].processor((BYTE *)stream->in.monoBuffer, frames, NULL, 0, processor[S_INPUT].userData);
+		}
+		else
+		{
+			processor[S_INPUT].processor(data, frames, NULL, 0, processor[S_INPUT].userData);
+		}
+
+		// Release buffer
+		if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, frames)) != S_OK)
+			return LogHostError(hr);
+
+		//break;
+	}
+
+	return hr;
+}
+
+// ------------------------------------------------------------------------------------------
+void _StreamOnStop(PaWasapiStream *stream)
+{
+	// Stop INPUT/OUTPUT clients
+	if (!stream->bBlocking) 
+	{
+		if (stream->in.clientProc != NULL)
+			IAudioClient_Stop(stream->in.clientProc);
+		if (stream->out.clientProc != NULL)
+			IAudioClient_Stop(stream->out.clientProc);
+	} 
+	else 
+	{
+		if (stream->in.clientParent != NULL)
+			IAudioClient_Stop(stream->in.clientParent);
+		if (stream->out.clientParent != NULL)
+			IAudioClient_Stop(stream->out.clientParent);
+	}
+
+	// Restore thread priority
+	if (stream->hAvTask != NULL)
+	{
+		PaWasapi_ThreadPriorityRevert(stream->hAvTask);
+		stream->hAvTask = NULL;
+	}
+
+    // Notify
+    if (stream->streamRepresentation.streamFinishedCallback != NULL)
+        stream->streamRepresentation.streamFinishedCallback(stream->streamRepresentation.userData);
+}
+
+// ------------------------------------------------------------------------------------------
+PA_THREAD_FUNC ProcThreadEvent(void *param)
+{
+    PaWasapiHostProcessor processor[S_COUNT];
+	HRESULT hr;
+	DWORD dwResult;
+    PaWasapiStream *stream = (PaWasapiStream *)param;
+	PaWasapiHostProcessor defaultProcessor;
+	BOOL set_event[S_COUNT] = { FALSE, FALSE };
+	BOOL bWaitAllEvents = FALSE;
+	BOOL bThreadComInitialized = FALSE;
+
+	/*
+	If COM is already initialized CoInitialize will either return
+	FALSE, or RPC_E_CHANGED_MODE if it was initialized in a different
+	threading mode. In either case we shouldn't consider it an error
+	but we need to be careful to not call CoUninitialize() if 
+	RPC_E_CHANGED_MODE was returned.
+	*/
+	hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
+	if (FAILED(hr) && (hr != RPC_E_CHANGED_MODE))
+	{
+		PRINT(("WASAPI: failed ProcThreadEvent CoInitialize"));
+		return paUnanticipatedHostError;
+	}
+	if (hr != RPC_E_CHANGED_MODE)
+		bThreadComInitialized = TRUE;
+
+	// Unmarshal stream pointers for safe COM operation
+	hr = UnmarshalStreamComPointers(stream);
+	if (hr != S_OK) {
+		PRINT(("Error unmarshaling stream COM pointers. HRESULT: %i\n", hr));
+		goto thread_end;
+	}
+
+	// Waiting on all events in case of Full-Duplex/Exclusive mode.
+	if ((stream->in.clientProc != NULL) && (stream->out.clientProc != NULL))
+	{
+		bWaitAllEvents = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) &&
+			(stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE);
+	}
+
+    // Setup data processors
+    defaultProcessor.processor = WaspiHostProcessingLoop;
+    defaultProcessor.userData  = stream;
+    processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
+    processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
+
+	// Boost thread priority
+	PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
+
+	// Create events
+	if (stream->event[S_OUTPUT] == NULL)
+	{
+		stream->event[S_OUTPUT] = CreateEvent(NULL, FALSE, FALSE, NULL);
+		set_event[S_OUTPUT] = TRUE;
+	}
+	if (stream->event[S_INPUT] == NULL)
+	{
+		stream->event[S_INPUT]  = CreateEvent(NULL, FALSE, FALSE, NULL);
+		set_event[S_INPUT] = TRUE;
+	}
+	if ((stream->event[S_OUTPUT] == NULL) || (stream->event[S_INPUT] == NULL))
+	{
+		PRINT(("WASAPI Thread: failed creating Input/Output event handle\n"));
+		goto thread_error;
+	}
+
+	// Initialize event & start INPUT stream
+	if (stream->in.clientProc)
+	{
+		// Create & set handle
+		if (set_event[S_INPUT])
+		{
+			if ((hr = IAudioClient_SetEventHandle(stream->in.clientProc, stream->event[S_INPUT])) != S_OK)
+			{
+				LogHostError(hr);
+				goto thread_error;
+			}
+		}
+
+		// Start
+		if ((hr = IAudioClient_Start(stream->in.clientProc)) != S_OK)
+		{
+			LogHostError(hr);
+			goto thread_error;
+		}
+	}
+
+	// Initialize event & start OUTPUT stream
+	if (stream->out.clientProc)
+	{
+		// Create & set handle
+		if (set_event[S_OUTPUT])
+		{
+			if ((hr = IAudioClient_SetEventHandle(stream->out.clientProc, stream->event[S_OUTPUT])) != S_OK)
+			{
+				LogHostError(hr);
+				goto thread_error;
+			}
+		}
+
+		// Preload buffer before start
+		if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
+		{
+			LogHostError(hr);
+			goto thread_error;
+		}
+
+		// Start
+		if ((hr = IAudioClient_Start(stream->out.clientProc)) != S_OK)
+		{
+			LogHostError(hr);
+			goto thread_error;
+		}
+
+	}
+
+	// Signal: stream running
+	stream->running = TRUE;
+
+	// Notify: thread started
+	SetEvent(stream->hThreadStart);
+
+	// Processing Loop
+	for (;;)
+    {
+	    // 10 sec timeout (on timeout stream will auto-stop when processed by WAIT_TIMEOUT case)
+        dwResult = WaitForMultipleObjects(S_COUNT, stream->event, bWaitAllEvents, 10*1000);
+
+		// Check for close event (after wait for buffers to avoid any calls to user
+		// callback when hCloseRequest was set)
+		if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
+			break;
+
+		// Process S_INPUT/S_OUTPUT
+		switch (dwResult)
+		{
+		case WAIT_TIMEOUT: {
+			PRINT(("WASAPI Thread: WAIT_TIMEOUT - probably bad audio driver or Vista x64 bug: use paWinWasapiPolling instead\n"));
+			goto thread_end;
+			break; }
+
+		// Input stream
+		case WAIT_OBJECT_0 + S_INPUT: {
+
+            if (stream->captureClient == NULL)
+                break;
+
+			if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
+			{
+				LogHostError(hr);
+				goto thread_error;
+			}
+
+			break; }
+
+		// Output stream
+		case WAIT_OBJECT_0 + S_OUTPUT: {
+
+            if (stream->renderClient == NULL)
+                break;
+
+			if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
+			{
+				LogHostError(hr);
+				goto thread_error;
+			}
+
+			break; }
+		}
+	}
+
+thread_end:
+
+	// Process stop
+	_StreamOnStop(stream);
+
+	// Release unmarshaled COM pointers
+	ReleaseUnmarshaledComPointers(stream);
+
+	// Cleanup COM for this thread
+	if (bThreadComInitialized == TRUE)
+		CoUninitialize();
+
+	// Notify: not running
+	stream->running = FALSE;
+
+	// Notify: thread exited
+	SetEvent(stream->hThreadExit);
+
+	return 0;
+
+thread_error:
+
+	// Prevent deadlocking in Pa_StreamStart
+	SetEvent(stream->hThreadStart);
+
+	// Exit
+	goto thread_end;
+}
+
+// ------------------------------------------------------------------------------------------
+PA_THREAD_FUNC ProcThreadPoll(void *param)
+{
+    PaWasapiHostProcessor processor[S_COUNT];
+	HRESULT hr;
+    PaWasapiStream *stream = (PaWasapiStream *)param;
+	PaWasapiHostProcessor defaultProcessor;
+	INT32 i;
+	ThreadIdleScheduler scheduler;
+
+	// Calculate the actual duration of the allocated buffer.
+	DWORD sleep_ms     = 0;
+	DWORD sleep_ms_in;
+	DWORD sleep_ms_out;
+
+	BOOL bThreadComInitialized = FALSE;
+
+	/*
+	If COM is already initialized CoInitialize will either return
+	FALSE, or RPC_E_CHANGED_MODE if it was initialized in a different
+	threading mode. In either case we shouldn't consider it an error
+	but we need to be careful to not call CoUninitialize() if 
+	RPC_E_CHANGED_MODE was returned.
+	*/
+	hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
+	if (FAILED(hr) && (hr != RPC_E_CHANGED_MODE))
+	{
+		PRINT(("WASAPI: failed ProcThreadPoll CoInitialize"));
+		return paUnanticipatedHostError;
+	}
+	if (hr != RPC_E_CHANGED_MODE)
+		bThreadComInitialized = TRUE;
+
+	// Unmarshal stream pointers for safe COM operation
+	hr = UnmarshalStreamComPointers(stream);
+	if (hr != S_OK) 
+	{
+		PRINT(("Error unmarshaling stream COM pointers. HRESULT: %i\n", hr));
+		return 0;
+	}
+
+	// Calculate timeout for next polling attempt.
+	sleep_ms_in  = GetFramesSleepTime(stream->in.framesPerHostCallback/WASAPI_PACKETS_PER_INPUT_BUFFER, stream->in.wavex.Format.nSamplesPerSec);
+	sleep_ms_out = GetFramesSleepTime(stream->out.framesPerBuffer, stream->out.wavex.Format.nSamplesPerSec);
+
+	// WASAPI Input packets tend to expire very easily, let's limit sleep time to 2 milliseconds
+	// for all cases. Please propose better solution if any.
+	if (sleep_ms_in > 2)
+		sleep_ms_in = 2;
+
+	// Adjust polling time for non-paUtilFixedHostBufferSize. Input stream is not adjustable as it is being
+	// polled according its packet length.
+	if (stream->bufferMode != paUtilFixedHostBufferSize)
+	{
+		//sleep_ms_in = GetFramesSleepTime(stream->bufferProcessor.framesPerUserBuffer, stream->in.wavex.Format.nSamplesPerSec);
+		sleep_ms_out = GetFramesSleepTime(stream->bufferProcessor.framesPerUserBuffer, stream->out.wavex.Format.nSamplesPerSec);
+	}
+
+	// Choose smallest
+	if ((sleep_ms_in != 0) && (sleep_ms_out != 0))
+		sleep_ms = min(sleep_ms_in, sleep_ms_out);
+	else
+	{
+		sleep_ms = (sleep_ms_in ? sleep_ms_in : sleep_ms_out);
+	}
+	// Make sure not 0, othervise use ThreadIdleScheduler
+	if (sleep_ms == 0)
+	{
+		sleep_ms_in  = GetFramesSleepTimeMicroseconds(stream->in.framesPerHostCallback/WASAPI_PACKETS_PER_INPUT_BUFFER, stream->in.wavex.Format.nSamplesPerSec);
+		sleep_ms_out = GetFramesSleepTimeMicroseconds(stream->bufferProcessor.framesPerUserBuffer, stream->out.wavex.Format.nSamplesPerSec);
+
+		// Choose smallest
+		if ((sleep_ms_in != 0) && (sleep_ms_out != 0))
+			sleep_ms = min(sleep_ms_in, sleep_ms_out);
+		else
+		{
+			sleep_ms = (sleep_ms_in ? sleep_ms_in : sleep_ms_out);
+		}
+
+		// Setup thread sleep scheduler
+		ThreadIdleScheduler_Setup(&scheduler, 1, sleep_ms/* microseconds here */);
+		sleep_ms = 0;
+	}
+
+    // Setup data processors
+    defaultProcessor.processor = WaspiHostProcessingLoop;
+    defaultProcessor.userData  = stream;
+    processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
+    processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
+
+	// Boost thread priority
+	PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
+
+	// Initialize event & start INPUT stream
+	if (stream->in.clientProc)
+	{
+		if ((hr = IAudioClient_Start(stream->in.clientProc)) != S_OK)
+		{
+			LogHostError(hr);
+			goto thread_error;
+		}
+	}
+
+	// Initialize event & start OUTPUT stream
+	if (stream->out.clientProc)
+	{
+		// Preload buffer (obligatory, othervise ->Start() will fail), avoid processing
+		// when in full-duplex mode as it requires input processing as well
+		if (!PA_WASAPI__IS_FULLDUPLEX(stream))
+		{
+			UINT32 frames = 0;
+			if ((hr = _PollGetOutputFramesAvailable(stream, &frames)) == S_OK)
+            {
+				if (stream->bufferMode == paUtilFixedHostBufferSize)
+				{
+					if (frames >= stream->out.framesPerBuffer)
+					{
+						frames = stream->out.framesPerBuffer;
+
+						if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
+						{
+							LogHostError(hr); // not fatal, just log
+						}
+					}
+				}
+				else
+				{
+					if (frames != 0)
+					{
+						if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
+						{
+							LogHostError(hr); // not fatal, just log
+						}
+					}
+				}
+            }
+            else
+			{
+				LogHostError(hr); // not fatal, just log
+			}
+		}
+
+		// Start
+		if ((hr = IAudioClient_Start(stream->out.clientProc)) != S_OK)
+		{
+			LogHostError(hr);
+			goto thread_error;
+		}
+	}
+
+	// Signal: stream running
+	stream->running = TRUE;
+
+	// Notify: thread started
+	SetEvent(stream->hThreadStart);
+
+	if (!PA_WASAPI__IS_FULLDUPLEX(stream))
+	{
+		// Processing Loop
+		UINT32 next_sleep = sleep_ms;
+		while (WaitForSingleObject(stream->hCloseRequest, next_sleep) == WAIT_TIMEOUT)
+		{
+			// Get next sleep time
+			if (sleep_ms == 0)
+			{
+				next_sleep = ThreadIdleScheduler_NextSleep(&scheduler);
+			}
+
+			for (i = 0; i < S_COUNT; ++i)
+			{
+				// Process S_INPUT/S_OUTPUT
+				switch (i)
+				{
+				// Input stream
+				case S_INPUT: {
+
+					if (stream->captureClient == NULL)
+						break;
+
+					if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
+					{
+						LogHostError(hr);
+						goto thread_error;
+					}
+
+					break; }
+
+				// Output stream
+				case S_OUTPUT: {
+
+					UINT32 frames;
+					if (stream->renderClient == NULL)
+						break;
+
+					// get available frames
+					if ((hr = _PollGetOutputFramesAvailable(stream, &frames)) != S_OK)
+					{
+						LogHostError(hr);
+						goto thread_error;
+					}
+
+					// output
+					if (stream->bufferMode == paUtilFixedHostBufferSize)
+					{
+						while (frames >= stream->out.framesPerBuffer)
+						{
+							if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
+							{
+								LogHostError(hr);
+								goto thread_error;
+							}
+
+							frames -= stream->out.framesPerBuffer;
+						}
+					}
+					else
+					{
+						if (frames != 0)
+						{
+							if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
+							{
+								LogHostError(hr);
+								goto thread_error;
+							}
+						}
+					}
+
+					break; }
+				}
+			}
+		}
+	}
+	else
+	{
+#if 0
+		// Processing Loop
+		while (WaitForSingleObject(stream->hCloseRequest, 1) == WAIT_TIMEOUT)
+		{
+			UINT32 i_frames = 0, i_processed = 0;
+			BYTE *i_data = NULL, *o_data = NULL, *o_data_host = NULL;
+			DWORD i_flags = 0;
+			UINT32 o_frames = 0;
+
+			// get host input buffer
+			if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &i_data, &i_frames, &i_flags, NULL, NULL)) != S_OK)
+			{
+				if (hr == AUDCLNT_S_BUFFER_EMPTY)
+					continue; // no data in capture buffer
+
+				LogHostError(hr);
+				break;
+			}
+
+			// get available frames
+			if ((hr = _PollGetOutputFramesAvailable(stream, &o_frames)) != S_OK)
+			{
+				// release input buffer
+				IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+
+				LogHostError(hr);
+				break;
+			}
+
+			// process equal ammount of frames
+			if (o_frames >= i_frames)
+			{
+				// process input ammount of frames
+				UINT32 o_processed = i_frames;
+
+				// get host output buffer
+				if ((hr = IAudioRenderClient_GetBuffer(stream->procRCClient, o_processed, &o_data)) == S_OK)
+				{
+					// processed amount of i_frames
+					i_processed = i_frames;
+					o_data_host = o_data;
+
+					// convert output mono
+					if (stream->out.monoMixer)
+					{
+						UINT32 mono_frames_size = o_processed * (stream->out.wavex.Format.wBitsPerSample / 8);
+						// expand buffer
+						if (mono_frames_size > stream->out.monoBufferSize)
+						{
+							stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
+							if (stream->out.monoBuffer == NULL)
+							{
+								// release input buffer
+								IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+								// release output buffer
+								IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+								LogPaError(paInsufficientMemory);
+								break;
+							}
+						}
+
+						// replace buffer pointer
+						o_data = (BYTE *)stream->out.monoBuffer;
+					}
+
+					// convert input mono
+					if (stream->in.monoMixer)
+					{
+						UINT32 mono_frames_size = i_processed * (stream->in.wavex.Format.wBitsPerSample / 8);
+						// expand buffer
+						if (mono_frames_size > stream->in.monoBufferSize)
+						{
+							stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
+							if (stream->in.monoBuffer == NULL)
+							{
+								// release input buffer
+								IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+								// release output buffer
+								IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+								LogPaError(paInsufficientMemory);
+								break;
+							}
+						}
+
+						// mix 2 to 1 input channels
+						stream->in.monoMixer(stream->in.monoBuffer, i_data, i_processed);
+
+						// replace buffer pointer
+						i_data = (BYTE *)stream->in.monoBuffer;
+					}
+
+					// process
+					processor[S_FULLDUPLEX].processor(i_data, i_processed, o_data, o_processed, processor[S_FULLDUPLEX].userData);
+
+					// mix 1 to 2 output channels
+					if (stream->out.monoBuffer)
+						stream->out.monoMixer(o_data_host, stream->out.monoBuffer, o_processed);
+
+					// release host output buffer
+					if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, o_processed, 0)) != S_OK)
+						LogHostError(hr);
+				}
+				else
+				{
+					if (stream->out.shareMode != AUDCLNT_SHAREMODE_SHARED)
+						LogHostError(hr); // be silent in shared mode, try again next time
+				}
+			}
+
+			// release host input buffer
+			if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, i_processed)) != S_OK)
+			{
+				LogHostError(hr);
+				break;
+			}
+		}
+#else
+		// Processing Loop
+		UINT32 next_sleep = sleep_ms;
+		while (WaitForSingleObject(stream->hCloseRequest, next_sleep) == WAIT_TIMEOUT)
+		{
+			UINT32 i_frames = 0, i_processed = 0;
+			BYTE *i_data = NULL, *o_data = NULL, *o_data_host = NULL;
+			DWORD i_flags = 0;
+			UINT32 o_frames = 0;
+
+			// Get next sleep time
+			if (sleep_ms == 0)
+			{
+				next_sleep = ThreadIdleScheduler_NextSleep(&scheduler);
+			}
+
+			// get available frames
+			if ((hr = _PollGetOutputFramesAvailable(stream, &o_frames)) != S_OK)
+			{
+				LogHostError(hr);
+				break;
+			}
+
+			while (o_frames != 0)
+			{
+				// get host input buffer
+				if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &i_data, &i_frames, &i_flags, NULL, NULL)) != S_OK)
+				{
+					if (hr == AUDCLNT_S_BUFFER_EMPTY)
+						break; // no data in capture buffer
+
+					LogHostError(hr);
+					break;
+				}
+
+				// process equal ammount of frames
+				if (o_frames >= i_frames)
+				{
+					// process input ammount of frames
+					UINT32 o_processed = i_frames;
+
+					// get host output buffer
+					if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, o_processed, &o_data)) == S_OK)
+					{
+						// processed amount of i_frames
+						i_processed = i_frames;
+						o_data_host = o_data;
+
+						// convert output mono
+						if (stream->out.monoMixer)
+						{
+							UINT32 mono_frames_size = o_processed * (stream->out.wavex.Format.wBitsPerSample / 8);
+							// expand buffer
+							if (mono_frames_size > stream->out.monoBufferSize)
+							{
+								stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
+								if (stream->out.monoBuffer == NULL)
+								{
+									// release input buffer
+									IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+									// release output buffer
+									IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+									LogPaError(paInsufficientMemory);
+									goto thread_error;
+								}
+							}
+
+							// replace buffer pointer
+							o_data = (BYTE *)stream->out.monoBuffer;
+						}
+
+						// convert input mono
+						if (stream->in.monoMixer)
+						{
+							UINT32 mono_frames_size = i_processed * (stream->in.wavex.Format.wBitsPerSample / 8);
+							// expand buffer
+							if (mono_frames_size > stream->in.monoBufferSize)
+							{
+								stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
+								if (stream->in.monoBuffer == NULL)
+								{
+									// release input buffer
+									IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
+									// release output buffer
+									IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
+
+									LogPaError(paInsufficientMemory);
+									goto thread_error;
+								}
+							}
+
+							// mix 2 to 1 input channels
+							stream->in.monoMixer(stream->in.monoBuffer, i_data, i_processed);
+
+							// replace buffer pointer
+							i_data = (BYTE *)stream->in.monoBuffer;
+						}
+
+						// process
+						processor[S_FULLDUPLEX].processor(i_data, i_processed, o_data, o_processed, processor[S_FULLDUPLEX].userData);
+
+						// mix 1 to 2 output channels
+						if (stream->out.monoBuffer)
+							stream->out.monoMixer(o_data_host, stream->out.monoBuffer, o_processed);
+
+						// release host output buffer
+						if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, o_processed, 0)) != S_OK)
+							LogHostError(hr);
+
+						o_frames -= o_processed;
+					}
+					else
+					{
+						if (stream->out.shareMode != AUDCLNT_SHAREMODE_SHARED)
+							LogHostError(hr); // be silent in shared mode, try again next time
+					}
+				}
+				else
+				{
+					i_processed = 0;
+					goto fd_release_buffer_in;
+				}
+
+fd_release_buffer_in:
+
+				// release host input buffer
+				if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, i_processed)) != S_OK)
+				{
+					LogHostError(hr);
+					break;
+				}
+
+				// break processing, input hasn't been accumulated yet
+				if (i_processed == 0)
+					break;
+			}
+		}
+#endif
+	}
+
+thread_end:
+
+	// Process stop
+	_StreamOnStop(stream);
+
+	// Release unmarshaled COM pointers
+	ReleaseUnmarshaledComPointers(stream);
+
+	// Cleanup COM for this thread
+	if (bThreadComInitialized == TRUE)
+		CoUninitialize();
+
+	// Notify: not running
+	stream->running = FALSE;
+
+	// Notify: thread exited
+	SetEvent(stream->hThreadExit);
+
+	return 0;
+
+thread_error:
+
+	// Prevent deadlocking in Pa_StreamStart
+	SetEvent(stream->hThreadStart);
+
+	// Exit
+	goto thread_end;
+}
+
+// ------------------------------------------------------------------------------------------
+void *PaWasapi_ReallocateMemory(void *ptr, size_t size)
+{
+	return realloc(ptr, size);
+}
+
+// ------------------------------------------------------------------------------------------
+void PaWasapi_FreeMemory(void *ptr)
+{
+	free(ptr);
+}
+
+//#endif //VC 2005
+
+
+
+
+#if 0
+			if(bFirst) {
+				float masteur;
+				hr = stream->outVol->GetMasterVolumeLevelScalar(&masteur);
+				if (hr != S_OK)
+					LogHostError(hr);
+				float chan1, chan2;
+				hr = stream->outVol->GetChannelVolumeLevelScalar(0, &chan1);
+				if (hr != S_OK)
+					LogHostError(hr);
+				hr = stream->outVol->GetChannelVolumeLevelScalar(1, &chan2);
+				if (hr != S_OK)
+					LogHostError(hr);
+
+				BOOL bMute;
+				hr = stream->outVol->GetMute(&bMute);
+				if (hr != S_OK)
+					LogHostError(hr);
+
+				stream->outVol->SetMasterVolumeLevelScalar(0.5, NULL);
+				stream->outVol->SetChannelVolumeLevelScalar(0, 0.5, NULL);
+				stream->outVol->SetChannelVolumeLevelScalar(1, 0.5, NULL);
+				stream->outVol->SetMute(FALSE, NULL);
+				bFirst = FALSE;
+			}
+#endif
+ portaudio/src/hostapi/wdmks/pa_win_wdmks.c view
@@ -0,0 +1,6655 @@+/*+* $Id: pa_win_wdmks.c 1885 2012-12-28 16:54:25Z robiwan $+* PortAudio Windows WDM-KS interface+*+* Author: Andrew Baldwin, Robert Bielik (WaveRT)+* Based on the Open Source API proposed by Ross Bencina+* Copyright (c) 1999-2004 Andrew Baldwin, Ross Bencina, Phil Burk+*+* Permission is hereby granted, free of charge, to any person obtaining+* a copy of this software and associated documentation files+* (the "Software"), to deal in the Software without restriction,+* including without limitation the rights to use, copy, modify, merge,+* publish, distribute, sublicense, and/or sell copies of the Software,+* and to permit persons to whom the Software is furnished to do so,+* subject to the following conditions:+*+* The above copyright notice and this permission notice shall be+* included in all copies or substantial portions of the Software.+*+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+*/++/*+* The text above constitutes the entire PortAudio license; however, +* the PortAudio community also makes the following non-binding requests:+*+* Any person wishing to distribute modifications to the Software is+* requested to send the modifications to the original developer so that+* they can be incorporated into the canonical version. It is also +* requested that these non-binding requests be included along with the +* license above.+*/++/** @file+@ingroup hostapi_src+@brief Portaudio WDM-KS host API.++@note This is the implementation of the Portaudio host API using the+Windows WDM/Kernel Streaming API in order to enable very low latency+playback and recording on all modern Windows platforms (e.g. 2K, XP, Vista, Win7)+Note: This API accesses the device drivers below the usual KMIXER+component which is normally used to enable multi-client mixing and+format conversion. That means that it will lock out all other users+of a device for the duration of active stream using those devices+*/++#include <stdio.h>++#if (defined(_WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */+#pragma comment( lib, "setupapi.lib" )+#endif++/* Debugging/tracing support */++#define PA_LOGE_+#define PA_LOGL_++#ifdef __GNUC__+#include <initguid.h>+#define _WIN32_WINNT 0x0501+#define WINVER 0x0501+#endif++#include <string.h> /* strlen() */+#include <assert.h>+#include <wchar.h>  /* iswspace() */++#include "pa_util.h"+#include "pa_allocation.h"+#include "pa_hostapi.h"+#include "pa_stream.h"+#include "pa_cpuload.h"+#include "pa_process.h"+#include "portaudio.h"+#include "pa_debugprint.h"+#include "pa_memorybarrier.h"+#include "pa_ringbuffer.h"+#include "pa_trace.h"+#include "pa_win_waveformat.h"++#include "pa_win_wdmks.h"++#include <windows.h>+#include <winioctl.h>+#include <process.h>++#include <math.h>++#ifdef _MSC_VER+#define snprintf _snprintf+#define vsnprintf _vsnprintf+#endif++/* The PA_HP_TRACE macro is used in RT parts, so it can be switched off without affecting+the rest of the debug tracing */+#if 1+#define PA_HP_TRACE(x)  PaUtil_AddHighSpeedLogMessage x ;+#else+#define PA_HP_TRACE(x)+#endif++/* A define that selects whether the resulting pin names are chosen from pin category+instead of the available pin names, who sometimes can be quite cheesy, like "Volume control".+Default is to use the pin category.+*/+#ifndef PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES+#define PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES  1+#endif++#ifdef __GNUC__+#undef PA_LOGE_+#define PA_LOGE_ PA_DEBUG(("%s {\n",__FUNCTION__))+#undef PA_LOGL_+#define PA_LOGL_ PA_DEBUG(("} %s\n",__FUNCTION__))+/* These defines are set in order to allow the WIndows DirectX+* headers to compile with a GCC compiler such as MinGW+* NOTE: The headers may generate a few warning in GCC, but+* they should compile */+#define _INC_MMSYSTEM+#define _INC_MMREG+#define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */+#define DEFINE_GUID_THUNK(name,guid) DEFINE_GUID(name,guid)+#define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK( n, STATIC_##n )+#if !defined( DEFINE_WAVEFORMATEX_GUID )+#define DEFINE_WAVEFORMATEX_GUID(x) (USHORT)(x), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71+#endif+#define  WAVE_FORMAT_ADPCM      0x0002+#define  WAVE_FORMAT_IEEE_FLOAT 0x0003+#define  WAVE_FORMAT_ALAW       0x0006+#define  WAVE_FORMAT_MULAW      0x0007+#define  WAVE_FORMAT_MPEG       0x0050+#define  WAVE_FORMAT_DRM        0x0009+#define DYNAMIC_GUID_THUNK(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}+#define DYNAMIC_GUID(data) DYNAMIC_GUID_THUNK(data)+#endif++/* use CreateThread for CYGWIN/Windows Mobile, _beginthreadex for all others */+#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)+#define CREATE_THREAD_FUNCTION (HANDLE)_beginthreadex+#define PA_THREAD_FUNC static unsigned WINAPI+#else+#define CREATE_THREAD_FUNCTION CreateThread+#define PA_THREAD_FUNC static DWORD WINAPI+#endif++#ifdef _MSC_VER+#define NOMMIDS+#define DYNAMIC_GUID(data) {data}+#define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */+#undef DEFINE_GUID+#define DEFINE_GUID(n,data) EXTERN_C const GUID n = {data}+#define DEFINE_GUID_THUNK(n,data) DEFINE_GUID(n,data)+#define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK(n, STATIC_##n)+#endif++#include <setupapi.h>++#ifndef EXTERN_C+#define EXTERN_C extern+#endif++#if defined(__GNUC__)++/* For MinGW we reference mingw-include files supplied with WASAPI */+#define WINBOOL BOOL++#include "../wasapi/mingw-include/ks.h"+#include "../wasapi/mingw-include/ksmedia.h"++#else++#include <mmreg.h>+#include <ks.h>++/* Note that Windows SDK V6.0A or later is needed for WaveRT specific structs to be present in+   ksmedia.h. Also make sure that the SDK include path is before other include paths (that may contain+   an "old" ksmedia.h), so the proper ksmedia.h is used */+#include <ksmedia.h>++#endif++#include <assert.h>+#include <stdio.h>++/* These next definitions allow the use of the KSUSER DLL */+typedef /*KSDDKAPI*/ DWORD WINAPI KSCREATEPIN(HANDLE, PKSPIN_CONNECT, ACCESS_MASK, PHANDLE);+extern HMODULE      DllKsUser;+extern KSCREATEPIN* FunctionKsCreatePin;++/* These definitions allows the use of AVRT.DLL on Vista and later OSs */+typedef enum _PA_AVRT_PRIORITY+{+    PA_AVRT_PRIORITY_LOW = -1,+    PA_AVRT_PRIORITY_NORMAL,+    PA_AVRT_PRIORITY_HIGH,+    PA_AVRT_PRIORITY_CRITICAL+} PA_AVRT_PRIORITY, *PPA_AVRT_PRIORITY;++typedef struct+{+    HINSTANCE hInstance;++    HANDLE  (WINAPI *AvSetMmThreadCharacteristics) (LPCSTR, LPDWORD);+    BOOL    (WINAPI *AvRevertMmThreadCharacteristics) (HANDLE);+    BOOL    (WINAPI *AvSetMmThreadPriority) (HANDLE, PA_AVRT_PRIORITY);+} PaWinWDMKSAvRtEntryPoints;++static PaWinWDMKSAvRtEntryPoints paWinWDMKSAvRtEntryPoints = {0};++/* An unspecified channel count (-1) is not treated correctly, so we replace it with+* an arbitrarily large number */ +#define MAXIMUM_NUMBER_OF_CHANNELS 256++/* Forward definition to break circular type reference between pin and filter */+struct __PaWinWdmFilter;+typedef struct __PaWinWdmFilter PaWinWdmFilter;++struct __PaWinWdmPin;+typedef struct __PaWinWdmPin PaWinWdmPin;++struct __PaWinWdmStream;+typedef struct __PaWinWdmStream PaWinWdmStream;++/* Function prototype for getting audio position */+typedef PaError (*FunctionGetPinAudioPosition)(PaWinWdmPin*, unsigned long*);++/* Function prototype for memory barrier */+typedef void (*FunctionMemoryBarrier)(void);++struct __PaProcessThreadInfo;+typedef struct __PaProcessThreadInfo PaProcessThreadInfo;++typedef PaError (*FunctionPinHandler)(PaProcessThreadInfo* pInfo, unsigned eventIndex);++typedef enum __PaStreamStartEnum+{+    StreamStart_kOk,+    StreamStart_kFailed,+    StreamStart_kCnt+} PaStreamStartEnum;++/* Multiplexed input structure.+*  Very often several physical inputs are multiplexed through a MUX node (represented in the topology filter) */+typedef struct __PaWinWdmMuxedInput+{+    wchar_t                     friendlyName[MAX_PATH];+    ULONG                       muxPinId;+    ULONG                       muxNodeId;+    ULONG                       endpointPinId;+} PaWinWdmMuxedInput;++/* The Pin structure+* A pin is an input or output node, e.g. for audio flow */+struct __PaWinWdmPin+{+    HANDLE                      handle;+    PaWinWdmMuxedInput**        inputs;+    unsigned                    inputCount;+    wchar_t                     friendlyName[MAX_PATH];++    PaWinWdmFilter*             parentFilter;+    PaWDMKSSubType              pinKsSubType;+    unsigned long               pinId;+    unsigned long               endpointPinId;  /* For output pins */+    KSPIN_CONNECT*              pinConnect;+    unsigned long               pinConnectSize;+    KSDATAFORMAT_WAVEFORMATEX*  ksDataFormatWfx;+    KSPIN_COMMUNICATION         communication;+    KSDATARANGE*                dataRanges;+    KSMULTIPLE_ITEM*            dataRangesItem;+    KSPIN_DATAFLOW              dataFlow;+    KSPIN_CINSTANCES            instances;+    unsigned long               frameSize;+    int                         maxChannels;+    unsigned long               formats;+    int                         defaultSampleRate;+    ULONG                       *positionRegister;  /* WaveRT */+    ULONG                       hwLatency;          /* WaveRT */+    FunctionMemoryBarrier       fnMemBarrier;       /* WaveRT */+    FunctionGetPinAudioPosition fnAudioPosition;    /* WaveRT */+    FunctionPinHandler          fnEventHandler;+    FunctionPinHandler          fnSubmitHandler;+};++/* The Filter structure+* A filter has a number of pins and a "friendly name" */+struct __PaWinWdmFilter+{+    HANDLE         handle;+    PaWinWDMKSDeviceInfo    devInfo;  /* This will hold information that is exposed in PaDeviceInfo */++    DWORD            deviceNode;+    int            pinCount;+    PaWinWdmPin**  pins;+    PaWinWdmFilter*  topologyFilter;+    wchar_t          friendlyName[MAX_PATH];+    int              validPinCount;+    int            usageCount;+    KSMULTIPLE_ITEM* connections;+    KSMULTIPLE_ITEM* nodes;+    int              filterRefCount;+};+++typedef struct __PaWinWdmDeviceInfo+{+    PaDeviceInfo    inheritedDeviceInfo;+    char            compositeName[MAX_PATH];   /* Composite name consists of pin name + device name in utf8 */+    PaWinWdmFilter* filter;+    unsigned long   pin;+    int             muxPosition;    /* Used only for input devices */+    int             endpointPinId;+}+PaWinWdmDeviceInfo;++/* PaWinWdmHostApiRepresentation - host api datastructure specific to this implementation */+typedef struct __PaWinWdmHostApiRepresentation+{+    PaUtilHostApiRepresentation  inheritedHostApiRep;+    PaUtilStreamInterface        callbackStreamInterface;+    PaUtilStreamInterface        blockingStreamInterface;++    PaUtilAllocationGroup*       allocations;+    int                          deviceCount;+}+PaWinWdmHostApiRepresentation;++typedef struct __DATAPACKET+{+    KSSTREAM_HEADER  Header;+    OVERLAPPED       Signal;+} DATAPACKET;++typedef struct __PaIOPacket+{+    DATAPACKET*     packet;+    unsigned        startByte;+    unsigned        lengthBytes;+} PaIOPacket;++typedef struct __PaWinWdmIOInfo+{+    PaWinWdmPin*        pPin;+    char*               hostBuffer;+    unsigned            hostBufferSize;+    unsigned            framesPerBuffer;+    unsigned            bytesPerFrame;+    unsigned            bytesPerSample;+    unsigned            noOfPackets;    /* Only used in WaveCyclic */+    HANDLE              *events;        /* noOfPackets handles (WaveCyclic) 1 (WaveRT) */+    DATAPACKET          *packets;       /* noOfPackets packets (WaveCyclic) 2 (WaveRT) */+    /* WaveRT polled mode */+    unsigned            lastPosition; +    unsigned            pollCntr;+} PaWinWdmIOInfo;++/* PaWinWdmStream - a stream data structure specifically for this implementation */+struct __PaWinWdmStream+{+    PaUtilStreamRepresentation  streamRepresentation;+    PaWDMKSSpecificStreamInfo   hostApiStreamInfo;    /* This holds info that is exposed through PaStreamInfo */+    PaUtilCpuLoadMeasurer       cpuLoadMeasurer;+    PaUtilBufferProcessor       bufferProcessor;++#if PA_TRACE_REALTIME_EVENTS+    LogHandle                   hLog;+#endif++    PaUtilAllocationGroup*      allocGroup;+    PaWinWdmIOInfo              capture;+    PaWinWdmIOInfo              render;+    int                         streamStarted;+    int                         streamActive;+    int                         streamStop;+    int                         streamAbort;+    int                         oldProcessPriority;+    HANDLE                      streamThread;+    HANDLE                      eventAbort;+    HANDLE                      eventStreamStart[StreamStart_kCnt];        /* 0 = OK, 1 = Failed */+    PaError                     threadResult;+    PaStreamFlags               streamFlags;++    /* Capture ring buffer */+    PaUtilRingBuffer            ringBuffer;+    char*                       ringBufferData;++    /* These values handle the case where the user wants to use fewer+    * channels than the device has */+    int                         userInputChannels;+    int                         deviceInputChannels;+    int                         userOutputChannels;+    int                         deviceOutputChannels;+};++/* Gather all processing variables in a struct */+struct __PaProcessThreadInfo +{+    PaWinWdmStream              *stream;+    PaStreamCallbackTimeInfo    ti;+    PaStreamCallbackFlags       underover;+    int                         cbResult;+    volatile int                pending;+    volatile int                priming;+    volatile int                pinsStarted;+    unsigned long               timeout;+    unsigned                    captureHead;+    unsigned                    captureTail;+    unsigned                    renderHead;+    unsigned                    renderTail;+    PaIOPacket                  capturePackets[4];+    PaIOPacket                  renderPackets[4];+};++/* Used for transferring device infos during scanning / rescanning */+typedef struct __PaWinWDMScanDeviceInfosResults+{ +    PaDeviceInfo **deviceInfos;+    PaDeviceIndex defaultInputDevice;+    PaDeviceIndex defaultOutputDevice;+} PaWinWDMScanDeviceInfosResults;++static const unsigned cPacketsArrayMask = 3;++HMODULE      DllKsUser = NULL;+KSCREATEPIN* FunctionKsCreatePin = NULL;++/* prototypes for functions declared in this file */++#ifdef __cplusplus+extern "C"+{+#endif /* __cplusplus */++    PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );++#ifdef __cplusplus+}+#endif /* __cplusplus */++/* Low level I/O functions */+static PaError WdmSyncIoctl(HANDLE handle,+                            unsigned long ioctlNumber,+                            void* inBuffer,+                            unsigned long inBufferCount,+                            void* outBuffer,+                            unsigned long outBufferCount,+                            unsigned long* bytesReturned);++static PaError WdmGetPropertySimple(HANDLE handle,+                                    const GUID* const guidPropertySet,+                                    unsigned long property,+                                    void* value,+                                    unsigned long valueCount);++static PaError WdmSetPropertySimple(HANDLE handle,+                                    const GUID* const guidPropertySet,+                                    unsigned long property,+                                    void* value,+                                    unsigned long valueCount,+                                    void* instance,+                                    unsigned long instanceCount);++static PaError WdmGetPinPropertySimple(HANDLE  handle,+                                       unsigned long pinId,+                                       const GUID* const guidPropertySet,+                                       unsigned long property,+                                       void* value,+                                       unsigned long valueCount,+                                       unsigned long* byteCount);++static PaError WdmGetPinPropertyMulti(HANDLE  handle,+                                      unsigned long pinId,+                                      const GUID* const guidPropertySet,+                                      unsigned long property,+                                      KSMULTIPLE_ITEM** ksMultipleItem);++static PaError WdmGetPropertyMulti(HANDLE handle,+                                   const GUID* const guidPropertySet,+                                   unsigned long property,+                                   KSMULTIPLE_ITEM** ksMultipleItem);++static PaError WdmSetMuxNodeProperty(HANDLE handle,+                                     ULONG nodeId,+                                     ULONG pinId);+++/** Pin management functions */+static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error);+static void PinFree(PaWinWdmPin* pin);+static void PinClose(PaWinWdmPin* pin);+static PaError PinInstantiate(PaWinWdmPin* pin);+/*static PaError PinGetState(PaWinWdmPin* pin, KSSTATE* state); NOT USED */+static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state);+static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format);+static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format);+/* WaveRT support */+static PaError PinQueryNotificationSupport(PaWinWdmPin* pPin, BOOL* pbResult);+static PaError PinGetBuffer(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier);+static PaError PinRegisterPositionRegister(PaWinWdmPin* pPin);+static PaError PinRegisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle);+static PaError PinUnregisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle);+static PaError PinGetHwLatency(PaWinWdmPin* pPin, ULONG* pFifoSize, ULONG* pChipsetDelay, ULONG* pCodecDelay);+static PaError PinGetAudioPositionDirect(PaWinWdmPin* pPin, ULONG* pPosition);+static PaError PinGetAudioPositionViaIOCTL(PaWinWdmPin* pPin, ULONG* pPosition);++/* Filter management functions */+static PaWinWdmFilter* FilterNew(PaWDMKSType type, DWORD devNode, const wchar_t* filterName, const wchar_t* friendlyName, PaError* error);+static PaError FilterInitializePins(PaWinWdmFilter* filter);+static void FilterFree(PaWinWdmFilter* filter);+static void FilterAddRef(PaWinWdmFilter* filter);+static PaWinWdmPin* FilterCreatePin(+                                    PaWinWdmFilter* filter,+                                    int pinId,+                                    const WAVEFORMATEX* wfex,+                                    PaError* error);+static PaError FilterUse(PaWinWdmFilter* filter);+static void FilterRelease(PaWinWdmFilter* filter);++/* Hot plug functions */+static BOOL IsDeviceTheSame(const PaWinWdmDeviceInfo* pDev1,+                            const PaWinWdmDeviceInfo* pDev2);++/* Interface functions */+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );+static PaError IsFormatSupported(+struct PaUtilHostApiRepresentation *hostApi,+    const PaStreamParameters *inputParameters,+    const PaStreamParameters *outputParameters,+    double sampleRate );++static PaError ScanDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void **newDeviceInfos, int *newDeviceCount );+static PaError CommitDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void *deviceInfos, int deviceCount );+static PaError DisposeDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, void *deviceInfos, int deviceCount );++static PaError OpenStream(+struct PaUtilHostApiRepresentation *hostApi,+    PaStream** s,+    const PaStreamParameters *inputParameters,+    const PaStreamParameters *outputParameters,+    double sampleRate,+    unsigned long framesPerBuffer,+    PaStreamFlags streamFlags,+    PaStreamCallback *streamCallback,+    void *userData );+static PaError CloseStream( PaStream* stream );+static PaError StartStream( PaStream *stream );+static PaError StopStream( PaStream *stream );+static PaError AbortStream( PaStream *stream );+static PaError IsStreamStopped( PaStream *s );+static PaError IsStreamActive( PaStream *stream );+static PaTime GetStreamTime( PaStream *stream );+static double GetStreamCpuLoad( PaStream* stream );+static PaError ReadStream(+                          PaStream* stream,+                          void *buffer,+                          unsigned long frames );+static PaError WriteStream(+                           PaStream* stream,+                           const void *buffer,+                           unsigned long frames );+static signed long GetStreamReadAvailable( PaStream* stream );+static signed long GetStreamWriteAvailable( PaStream* stream );++/* Utility functions */+static unsigned long GetWfexSize(const WAVEFORMATEX* wfex);+static PaWinWdmFilter** BuildFilterList(int* filterCount, int* noOfPaDevices, PaError* result);+static BOOL PinWrite(HANDLE h, DATAPACKET* p);+static BOOL PinRead(HANDLE h, DATAPACKET* p);+static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples);+static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples);+PA_THREAD_FUNC ProcessingThread(void*);++/* Pin handler functions */+static PaError PaPinCaptureEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinCaptureSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);++static PaError PaPinRenderEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinRenderSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);++static PaError PaPinCaptureEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinCaptureEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinCaptureSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinCaptureSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);++static PaError PaPinRenderEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinRenderEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinRenderSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);+static PaError PaPinRenderSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);++/* Function bodies */++#if defined(_DEBUG) && defined(PA_ENABLE_DEBUG_OUTPUT)+#define PA_WDMKS_SET_TREF+static PaTime tRef = 0;++static void PaWinWdmDebugPrintf(const char* fmt, ...)+{+    va_list list;+    char buffer[1024];+    PaTime t = PaUtil_GetTime() - tRef;+    va_start(list, fmt);+    _vsnprintf(buffer, 1023, fmt, list);+    va_end(list);+    PaUtil_DebugPrint("%6.3lf: %s", t, buffer);+}++#ifdef PA_DEBUG+#undef PA_DEBUG+#define PA_DEBUG(x)    PaWinWdmDebugPrintf x ;+#endif+#endif++static BOOL IsDeviceTheSame(const PaWinWdmDeviceInfo* pDev1,+                            const PaWinWdmDeviceInfo* pDev2)+{+    if (pDev1 == NULL || pDev2 == NULL)+        return FALSE;++    if (pDev1 == pDev2)+        return TRUE;++    if (strcmp(pDev1->compositeName, pDev2->compositeName) == 0)+        return TRUE;++    return FALSE;+}++static BOOL IsEarlierThanVista()+{+    OSVERSIONINFO osvi;+    osvi.dwOSVersionInfoSize = sizeof(osvi);+    if (GetVersionEx(&osvi) && osvi.dwMajorVersion<6)+    {+        return TRUE;+    }+    return FALSE;+}++++static void MemoryBarrierDummy(void)+{+    /* Do nothing */+}++static void MemoryBarrierRead(void)+{+    PaUtil_ReadMemoryBarrier();+}++static void MemoryBarrierWrite(void)+{+    PaUtil_WriteMemoryBarrier();+}++static unsigned long GetWfexSize(const WAVEFORMATEX* wfex)+{+    if( wfex->wFormatTag == WAVE_FORMAT_PCM )+    {+        return sizeof( WAVEFORMATEX );+    }+    else+    {+        return (sizeof( WAVEFORMATEX ) + wfex->cbSize);+    }+}++static void PaWinWDM_SetLastErrorInfo(long errCode, const char* fmt, ...)+{+    va_list list;+    char buffer[1024];+    va_start(list, fmt);+    _vsnprintf(buffer, 1023, fmt, list);+    va_end(list);+    PaUtil_SetLastHostErrorInfo(paWDMKS, errCode, buffer);+}++/*+Low level pin/filter access functions+*/+static PaError WdmSyncIoctl(+                            HANDLE handle,+                            unsigned long ioctlNumber,+                            void* inBuffer,+                            unsigned long inBufferCount,+                            void* outBuffer,+                            unsigned long outBufferCount,+                            unsigned long* bytesReturned)+{+    PaError result = paNoError;+    unsigned long dummyBytesReturned = 0;+    BOOL bRes;++    if( !bytesReturned )+    {+        /* Use a dummy as the caller hasn't supplied one */+        bytesReturned = &dummyBytesReturned;+    }++    bRes = DeviceIoControl(handle, ioctlNumber, inBuffer, inBufferCount, outBuffer, outBufferCount, bytesReturned, NULL);+    if (!bRes)+    {+        unsigned long error = GetLastError();+        if ( !(((error == ERROR_INSUFFICIENT_BUFFER ) || ( error == ERROR_MORE_DATA )) && +            ( ioctlNumber == IOCTL_KS_PROPERTY ) &&+            ( outBufferCount == 0 ) ) ) +        {+            KSPROPERTY* ksProperty = (KSPROPERTY*)inBuffer;++            PaWinWDM_SetLastErrorInfo(result, "WdmSyncIoctl: DeviceIoControl GLE = 0x%08X (prop_set = {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}, prop_id = %u)",+                error,+                ksProperty->Set.Data1, ksProperty->Set.Data2, ksProperty->Set.Data3,+                ksProperty->Set.Data4[0], ksProperty->Set.Data4[1],+                ksProperty->Set.Data4[2], ksProperty->Set.Data4[3],+                ksProperty->Set.Data4[4], ksProperty->Set.Data4[5],+                ksProperty->Set.Data4[6], ksProperty->Set.Data4[7],+                ksProperty->Id+                );+            result = paUnanticipatedHostError;+        }+    }+    return result;+}++static PaError WdmGetPropertySimple(HANDLE handle,+                                    const GUID* const guidPropertySet,+                                    unsigned long property,+                                    void* value,+                                    unsigned long valueCount)+{+    PaError result;+    KSPROPERTY ksProperty;++    ksProperty.Set = *guidPropertySet;+    ksProperty.Id = property;+    ksProperty.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(+        handle,+        IOCTL_KS_PROPERTY,+        &ksProperty,+        sizeof(KSPROPERTY),+        value,+        valueCount,+        NULL);++    return result;+}++static PaError WdmSetPropertySimple(+                                    HANDLE handle,+                                    const GUID* const guidPropertySet,+                                    unsigned long property,+                                    void* value,+                                    unsigned long valueCount,+                                    void* instance,+                                    unsigned long instanceCount)+{+    PaError result;+    KSPROPERTY* ksProperty;+    unsigned long propertyCount  = 0;++    propertyCount = sizeof(KSPROPERTY) + instanceCount;+    ksProperty = (KSPROPERTY*)_alloca( propertyCount );+    if( !ksProperty )+    {+        return paInsufficientMemory;+    }++    ksProperty->Set = *guidPropertySet;+    ksProperty->Id = property;+    ksProperty->Flags = KSPROPERTY_TYPE_SET;++    if( instance )+    {+        memcpy((void*)((char*)ksProperty + sizeof(KSPROPERTY)), instance, instanceCount);+    }++    result = WdmSyncIoctl(+        handle,+        IOCTL_KS_PROPERTY,+        ksProperty,+        propertyCount,+        value,+        valueCount,+        NULL);++    return result;+}++static PaError WdmGetPinPropertySimple(+                                       HANDLE  handle,+                                       unsigned long pinId,+                                       const GUID* const guidPropertySet,+                                       unsigned long property,+                                       void* value,+                                       unsigned long valueCount,+                                       unsigned long *byteCount)+{+    PaError result;++    KSP_PIN ksPProp;+    ksPProp.Property.Set = *guidPropertySet;+    ksPProp.Property.Id = property;+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;+    ksPProp.PinId = pinId;+    ksPProp.Reserved = 0;++    result = WdmSyncIoctl(+        handle,+        IOCTL_KS_PROPERTY,+        &ksPProp,+        sizeof(KSP_PIN),+        value,+        valueCount,+        byteCount);++    return result;+}++static PaError WdmGetPinPropertyMulti(+                                      HANDLE handle,+                                      unsigned long pinId,+                                      const GUID* const guidPropertySet,+                                      unsigned long property,+                                      KSMULTIPLE_ITEM** ksMultipleItem)+{+    PaError result;+    unsigned long multipleItemSize = 0;+    KSP_PIN ksPProp;++    ksPProp.Property.Set = *guidPropertySet;+    ksPProp.Property.Id = property;+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;+    ksPProp.PinId = pinId;+    ksPProp.Reserved = 0;++    result = WdmSyncIoctl(+        handle,+        IOCTL_KS_PROPERTY,+        &ksPProp.Property,+        sizeof(KSP_PIN),+        NULL,+        0,+        &multipleItemSize);+    if( result != paNoError )+    {+        return result;+    }++    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );+    if( !*ksMultipleItem )+    {+        return paInsufficientMemory;+    }++    result = WdmSyncIoctl(+        handle,+        IOCTL_KS_PROPERTY,+        &ksPProp,+        sizeof(KSP_PIN),+        (void*)*ksMultipleItem,+        multipleItemSize,+        NULL);++    if( result != paNoError )+    {+        PaUtil_FreeMemory( ksMultipleItem );+    }++    return result;+}++static PaError WdmGetPropertyMulti(HANDLE handle,+                                   const GUID* const guidPropertySet,+                                   unsigned long property,+                                   KSMULTIPLE_ITEM** ksMultipleItem)+{+    PaError result;+    unsigned long multipleItemSize = 0;+    KSPROPERTY ksProp;++    ksProp.Set = *guidPropertySet;+    ksProp.Id = property;+    ksProp.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(+        handle,+        IOCTL_KS_PROPERTY,+        &ksProp,+        sizeof(KSPROPERTY),+        NULL,+        0,+        &multipleItemSize);+    if( result != paNoError )+    {+        return result;+    }++    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );+    if( !*ksMultipleItem )+    {+        return paInsufficientMemory;+    }++    result = WdmSyncIoctl(+        handle,+        IOCTL_KS_PROPERTY,+        &ksProp,+        sizeof(KSPROPERTY),+        (void*)*ksMultipleItem,+        multipleItemSize,+        NULL);++    if( result != paNoError )+    {+        PaUtil_FreeMemory( ksMultipleItem );+    }++    return result;+}++static PaError WdmSetMuxNodeProperty(HANDLE handle,+                                     ULONG nodeId,+                                     ULONG pinId)+{+    PaError result = paNoError;+    KSNODEPROPERTY prop;+    prop.Property.Set = KSPROPSETID_Audio;+    prop.Property.Id = KSPROPERTY_AUDIO_MUX_SOURCE;+    prop.Property.Flags = KSPROPERTY_TYPE_SET | KSPROPERTY_TYPE_TOPOLOGY;+    prop.NodeId = nodeId;+    prop.Reserved = 0;++    result = WdmSyncIoctl(handle, IOCTL_KS_PROPERTY, &prop, sizeof(KSNODEPROPERTY), &pinId, sizeof(ULONG), NULL);++    return result;+}++/* Used when traversing topology for outputs */+static const KSTOPOLOGY_CONNECTION* GetConnectionTo(const KSTOPOLOGY_CONNECTION* pFrom, PaWinWdmFilter* filter, int muxIdx)+{+    unsigned i;+    const KSTOPOLOGY_CONNECTION* retval = NULL;+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);+    (void)muxIdx;+    PA_DEBUG(("GetConnectionTo: Checking %u connections... (pFrom = %p)", filter->connections->Count, pFrom));+    for (i = 0; i < filter->connections->Count; ++i)+    {+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;+        if (pConn == pFrom)+            continue;++        if (pConn->FromNode == pFrom->ToNode)+        {+            retval = pConn;+            break;+        }+    }+    PA_DEBUG(("GetConnectionTo: Returning %p\n", retval));+    return retval;+}++/* Used when traversing topology for inputs */+static const KSTOPOLOGY_CONNECTION* GetConnectionFrom(const KSTOPOLOGY_CONNECTION* pTo, PaWinWdmFilter* filter, int muxIdx)+{+    unsigned i;+    const KSTOPOLOGY_CONNECTION* retval = NULL;+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);+    int muxCntr = 0;+    PA_DEBUG(("GetConnectionFrom: Checking %u connections... (pTo = %p)\n", filter->connections->Count, pTo));+    for (i = 0; i < filter->connections->Count; ++i)+    {+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;+        if (pConn == pTo)+            continue;++        if (pConn->ToNode == pTo->FromNode)+        {+            if (muxIdx >= 0)+            {+                if (muxCntr < muxIdx)+                {+                    ++muxCntr;+                    continue;+                }+            }+            retval = pConn;+            break;+        }+    }+    PA_DEBUG(("GetConnectionFrom: Returning %p\n", retval));+    return retval;+}++static ULONG GetNumberOfConnectionsTo(const KSTOPOLOGY_CONNECTION* pTo, PaWinWdmFilter* filter)+{+    ULONG retval = 0;+    unsigned i;+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);+    PA_DEBUG(("GetNumberOfConnectionsTo: Checking %u connections...", filter->connections->Count));+    for (i = 0; i < filter->connections->Count; ++i)+    {+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;+        if (pConn->ToNode == pTo->FromNode &&+            (pTo->FromNode != KSFILTER_NODE || pConn->ToNodePin == pTo->FromNodePin))+        {+            ++retval;+        }+    }+    return retval;+}++typedef const KSTOPOLOGY_CONNECTION *(*TFnGetConnection)(const KSTOPOLOGY_CONNECTION*, PaWinWdmFilter*, int);++static const KSTOPOLOGY_CONNECTION* FindStartConnectionFrom(ULONG startPin, PaWinWdmFilter* filter)+{+    unsigned i;+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);+    PA_DEBUG(("FindStartConnectionFrom: Checking %u connections...", filter->connections->Count));+    for (i = 0; i < filter->connections->Count; ++i)+    {+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;+        if (pConn->ToNode == KSFILTER_NODE && pConn->ToNodePin == startPin)+        {+            return pConn;+        }+    }++    assert(FALSE);+    return 0;+}++static const KSTOPOLOGY_CONNECTION* FindStartConnectionTo(ULONG startPin, PaWinWdmFilter* filter)+{+    unsigned i;+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);+    PA_DEBUG(("FindStartConnectionTo: Checking %u connections...", filter->connections->Count));+    for (i = 0; i < filter->connections->Count; ++i)+    {+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;+        if (pConn->FromNode == KSFILTER_NODE && pConn->FromNodePin == startPin)+        {+            return pConn;+        }+    }++    assert(FALSE);+    return 0;+}++static ULONG GetConnectedPin(ULONG startPin, BOOL forward, PaWinWdmFilter* filter, int muxPosition, ULONG *muxInputPinId, ULONG *muxNodeId)+{+    const KSTOPOLOGY_CONNECTION *conn = NULL; +    TFnGetConnection fnGetConnection = forward ? GetConnectionTo : GetConnectionFrom ;+    while (1)+    {+        if (conn == NULL)+        {+            conn = forward ? FindStartConnectionTo(startPin, filter) : FindStartConnectionFrom(startPin, filter);+        }+        else+        {+            conn = fnGetConnection(conn, filter, -1);+        }++        /* Handling case of erroneous connection list */+        if (conn == NULL)+        {+            break;+        }++        if (forward ? conn->ToNode == KSFILTER_NODE : conn->FromNode == KSFILTER_NODE)+        {+            return forward ? conn->ToNodePin : conn->FromNodePin;+        }+        else+        {+            PA_DEBUG(("GetConnectedPin: count=%d, forward=%d, muxPosition=%d\n", filter->nodes->Count, forward, muxPosition));+            if (filter->nodes->Count > 0 && !forward && muxPosition >= 0)+            {+                const GUID* nodes = (const GUID*)(filter->nodes + 1);+                if (IsEqualGUID(&nodes[conn->FromNode], &KSNODETYPE_MUX))+                {+                    ULONG nConn = GetNumberOfConnectionsTo(conn, filter);+                    conn = fnGetConnection(conn, filter, muxPosition);+                    if (conn == NULL)+                    {+                        break;+                    }+                    if (muxInputPinId != 0)+                    {+                        *muxInputPinId = conn->ToNodePin;+                    }+                    if (muxNodeId != 0)+                    {+                        *muxNodeId = conn->ToNode;+                    }+                }+            }+        }+    }+    return KSFILTER_NODE;+}++static void DumpConnectionsAndNodes(PaWinWdmFilter* filter)+{+    unsigned i;+    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);+    const GUID* nodes = (const GUID*)(filter->nodes + 1);++    PA_DEBUG(("DumpConnectionsAndNodes: connections=%d, nodes=%d\n", filter->connections->Count, filter->nodes->Count));++    for (i=0; i < filter->connections->Count; ++i)+    {+        const KSTOPOLOGY_CONNECTION* pConn = connections + i;+        PA_DEBUG(("  Connection: %u - FromNode=%u,FromPin=%u -> ToNode=%u,ToPin=%u\n", +            i,+            pConn->FromNode, pConn->FromNodePin,+            pConn->ToNode, pConn->ToNodePin+            ));+    }++    for (i=0; i < filter->nodes->Count; ++i)+    {+        const GUID* pConn = nodes + i;+        PA_DEBUG(("  Node: %d - {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",+            i,+            pConn->Data1, pConn->Data2, pConn->Data3,+            pConn->Data4[0], pConn->Data4[1],+            pConn->Data4[2], pConn->Data4[3],+            pConn->Data4[4], pConn->Data4[5],+            pConn->Data4[6], pConn->Data4[7]+        ));+    }++}++typedef struct __PaUsbTerminalGUIDToName +{+    USHORT     usbGUID;+    wchar_t    name[64];+} PaUsbTerminalGUIDToName;++static const PaUsbTerminalGUIDToName kNames[] =+{+    /* Types copied from: http://msdn.microsoft.com/en-us/library/ff537742(v=vs.85).aspx */+    /* Input terminal types */+    { 0x0201, L"Microphone" },+    { 0x0202, L"Desktop Microphone" },+    { 0x0203, L"Personal Microphone" },+    { 0x0204, L"Omni Directional Microphone" },+    { 0x0205, L"Microphone Array" },+    { 0x0206, L"Processing Microphone Array" },+    /* Output terminal types */+    { 0x0301, L"Speakers" },+    { 0x0302, L"Headphones" },+    { 0x0303, L"Head Mounted Display Audio" },+    { 0x0304, L"Desktop Speaker" },+    { 0x0305, L"Room Speaker" },+    { 0x0306, L"Communication Speaker" },+    { 0x0307, L"LFE Speakers" },+    /* External terminal types */+    { 0x0601, L"Analog" },+    { 0x0602, L"Digital" },+    { 0x0603, L"Line" },+    { 0x0604, L"Audio" },+    { 0x0605, L"SPDIF" },+};++static const unsigned kNamesCnt = sizeof(kNames)/sizeof(PaUsbTerminalGUIDToName);++static int PaUsbTerminalGUIDToNameCmp(const void* lhs, const void* rhs)+{+    const PaUsbTerminalGUIDToName* pL = (const PaUsbTerminalGUIDToName*)lhs;+    const PaUsbTerminalGUIDToName* pR = (const PaUsbTerminalGUIDToName*)rhs;+    return ((int)(pL->usbGUID) - (int)(pR->usbGUID));+}++static PaError GetNameFromCategory(const GUID* pGUID, BOOL input, wchar_t* name, unsigned length)+{+    PaError result = paUnanticipatedHostError;+    USHORT usbTerminalGUID = (USHORT)(pGUID->Data1 - 0xDFF219E0);++    if (input && usbTerminalGUID >= 0x301 && usbTerminalGUID < 0x400)+    {+        /* Output terminal name for an input !? Set it to Line! */+        usbTerminalGUID = 0x603;+    }+    if (!input && usbTerminalGUID >= 0x201 && usbTerminalGUID < 0x300)+    {+        /* Input terminal name for an output !? Set it to Line! */+        usbTerminalGUID = 0x603;+    }+    if (usbTerminalGUID >= 0x201 && usbTerminalGUID < 0x713)+    {+        PaUsbTerminalGUIDToName s = { usbTerminalGUID };+        const PaUsbTerminalGUIDToName* ptr = bsearch(+            &s,+            kNames,+            kNamesCnt,+            sizeof(PaUsbTerminalGUIDToName),+            PaUsbTerminalGUIDToNameCmp+            );+        if (ptr != 0)+        {+            PA_DEBUG(("GetNameFromCategory: USB GUID %04X -> '%S'\n", usbTerminalGUID, ptr->name));++            if (name != NULL && length > 0)+            {+                int n = _snwprintf(name, length, L"%s", ptr->name);+                if (usbTerminalGUID >= 0x601 && usbTerminalGUID < 0x700)+                {+                    _snwprintf(name + n, length - n, L" %s", (input ? L"In":L"Out"));+                }+            }+            result = paNoError;+        }+    }+    else+    {+        PaWinWDM_SetLastErrorInfo(result, "GetNameFromCategory: usbTerminalGUID = %04X ", usbTerminalGUID);+    }+    return result;+}++static BOOL IsFrequencyWithinRange(const KSDATARANGE_AUDIO* range, int frequency)+{+    if (frequency < (int)range->MinimumSampleFrequency)+        return FALSE;+    if (frequency > (int)range->MaximumSampleFrequency)+        return FALSE;+    return TRUE;+}++static BOOL IsBitsWithinRange(const KSDATARANGE_AUDIO* range, int noOfBits)+{+    if (noOfBits < (int)range->MinimumBitsPerSample)+        return FALSE;+    if (noOfBits > (int)range->MaximumBitsPerSample)+        return FALSE;+    return TRUE;+}++/* Note: Somewhat different order compared to WMME implementation, as we want to focus on fidelity first */+static const int defaultSampleRateSearchOrder[] =+{ 44100, 48000, 88200, 96000, 192000, 32000, 24000, 22050, 16000, 12000, 11025, 9600, 8000 };+static const int defaultSampleRateSearchOrderCount = sizeof(defaultSampleRateSearchOrder)/sizeof(defaultSampleRateSearchOrder[0]);++static int DefaultSampleFrequencyIndex(const KSDATARANGE_AUDIO* range)+{+    int i;++    for(i=0; i < defaultSampleRateSearchOrderCount; ++i)+    {+        int currentFrequency = defaultSampleRateSearchOrder[i];++        if (IsFrequencyWithinRange(range, currentFrequency))+        {+            return i;+        }+    }++    return -1;+}++/*+Create a new pin object belonging to a filter+The pin object holds all the configuration information about the pin+before it is opened, and then the handle of the pin after is opened+*/+static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error)+{+    PaWinWdmPin* pin;+    PaError result;+    unsigned long i;+    KSMULTIPLE_ITEM* item = NULL;+    KSIDENTIFIER* identifier;+    KSDATARANGE* dataRange;+    const ULONG streamingId = (parentFilter->devInfo.streamingType == Type_kWaveRT) ? KSINTERFACE_STANDARD_LOOPED_STREAMING : KSINTERFACE_STANDARD_STREAMING;+    int defaultSampleRateIndex = defaultSampleRateSearchOrderCount;++    PA_LOGE_;+    PA_DEBUG(("PinNew: Creating pin %d:\n",pinId));++    /* Allocate the new PIN object */+    pin = (PaWinWdmPin*)PaUtil_AllocateMemory( sizeof(PaWinWdmPin) );+    if( !pin )+    {+        result = paInsufficientMemory;+        goto error;+    }++    /* Zero the pin object */+    /* memset( (void*)pin, 0, sizeof(PaWinWdmPin) ); */++    pin->parentFilter = parentFilter;+    pin->pinId = pinId;++    /* Allocate a connect structure */+    pin->pinConnectSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX);+    pin->pinConnect = (KSPIN_CONNECT*)PaUtil_AllocateMemory( pin->pinConnectSize );+    if( !pin->pinConnect )+    {+        result = paInsufficientMemory;+        goto error;+    }++    /* Configure the connect structure with default values */+    pin->pinConnect->Interface.Set               = KSINTERFACESETID_Standard;+    pin->pinConnect->Interface.Id                = streamingId;+    pin->pinConnect->Interface.Flags             = 0;+    pin->pinConnect->Medium.Set                  = KSMEDIUMSETID_Standard;+    pin->pinConnect->Medium.Id                   = KSMEDIUM_TYPE_ANYINSTANCE;+    pin->pinConnect->Medium.Flags                = 0;+    pin->pinConnect->PinId                       = pinId;+    pin->pinConnect->PinToHandle                 = NULL;+    pin->pinConnect->Priority.PriorityClass      = KSPRIORITY_NORMAL;+    pin->pinConnect->Priority.PrioritySubClass   = 1;+    pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)(pin->pinConnect + 1);+    pin->ksDataFormatWfx->DataFormat.FormatSize  = sizeof(KSDATAFORMAT_WAVEFORMATEX);+    pin->ksDataFormatWfx->DataFormat.Flags       = 0;+    pin->ksDataFormatWfx->DataFormat.Reserved    = 0;+    pin->ksDataFormatWfx->DataFormat.MajorFormat = KSDATAFORMAT_TYPE_AUDIO;+    pin->ksDataFormatWfx->DataFormat.SubFormat   = KSDATAFORMAT_SUBTYPE_PCM;+    pin->ksDataFormatWfx->DataFormat.Specifier   = KSDATAFORMAT_SPECIFIER_WAVEFORMATEX;++    pin->frameSize = 0; /* Unknown until we instantiate pin */++    /* Get the COMMUNICATION property */+    result = WdmGetPinPropertySimple(+        parentFilter->handle,+        pinId,+        &KSPROPSETID_Pin,+        KSPROPERTY_PIN_COMMUNICATION,+        &pin->communication,+        sizeof(KSPIN_COMMUNICATION),+        NULL);+    if( result != paNoError )+        goto error;++    if( /*(pin->communication != KSPIN_COMMUNICATION_SOURCE) &&*/+        (pin->communication != KSPIN_COMMUNICATION_SINK) &&+        (pin->communication != KSPIN_COMMUNICATION_BOTH) )+    {+        PA_DEBUG(("PinNew: Not source/sink\n"));+        result = paInvalidDevice;+        goto error;+    }++    /* Get dataflow information */+    result = WdmGetPinPropertySimple(+        parentFilter->handle,+        pinId,+        &KSPROPSETID_Pin,+        KSPROPERTY_PIN_DATAFLOW,+        &pin->dataFlow,+        sizeof(KSPIN_DATAFLOW),+        NULL);++    if( result != paNoError )+        goto error;++    /* Get the INTERFACE property list */+    result = WdmGetPinPropertyMulti(+        parentFilter->handle,+        pinId,+        &KSPROPSETID_Pin,+        KSPROPERTY_PIN_INTERFACES,+        &item);++    if( result != paNoError )+        goto error;++    identifier = (KSIDENTIFIER*)(item+1);++    /* Check that at least one interface is STANDARD_STREAMING */+    result = paUnanticipatedHostError;+    for( i = 0; i < item->Count; i++ )+    {+        if( IsEqualGUID(&identifier[i].Set, &KSINTERFACESETID_Standard) && ( identifier[i].Id == streamingId ) )+        {+            result = paNoError;+            break;+        }+    }++    if( result != paNoError )+    {+        PA_DEBUG(("PinNew: No %s streaming\n", streamingId==KSINTERFACE_STANDARD_LOOPED_STREAMING?"looped":"standard"));+        goto error;+    }++    /* Don't need interfaces any more */+    PaUtil_FreeMemory( item );+    item = NULL;++    /* Get the MEDIUM properties list */+    result = WdmGetPinPropertyMulti(+        parentFilter->handle,+        pinId,+        &KSPROPSETID_Pin,+        KSPROPERTY_PIN_MEDIUMS,+        &item);++    if( result != paNoError )+        goto error;++    identifier = (KSIDENTIFIER*)(item+1); /* Not actually necessary... */++    /* Check that at least one medium is STANDARD_DEVIO */+    result = paUnanticipatedHostError;+    for( i = 0; i < item->Count; i++ )+    {+        if( IsEqualGUID(&identifier[i].Set, &KSMEDIUMSETID_Standard) && ( identifier[i].Id == KSMEDIUM_STANDARD_DEVIO ) )+        {+            result = paNoError;+            break;+        }+    }++    if( result != paNoError )+    {+        PA_DEBUG(("No standard devio\n"));+        goto error;+    }+    /* Don't need mediums any more */+    PaUtil_FreeMemory( item );+    item = NULL;++    /* Get DATARANGES */+    result = WdmGetPinPropertyMulti(+        parentFilter->handle,+        pinId,+        &KSPROPSETID_Pin,+        KSPROPERTY_PIN_DATARANGES,+        &pin->dataRangesItem);++    if( result != paNoError )+        goto error;++    pin->dataRanges = (KSDATARANGE*)(pin->dataRangesItem +1);++    /* Check that at least one datarange supports audio */+    result = paUnanticipatedHostError;+    dataRange = pin->dataRanges;+    pin->maxChannels = 0;+    pin->defaultSampleRate = 0;+    pin->formats = 0;+    PA_DEBUG(("PinNew: Checking %u no of dataranges...\n", pin->dataRangesItem->Count));+    for( i = 0; i < pin->dataRangesItem->Count; i++)+    {+        PA_DEBUG(("PinNew: DR major format %x\n",*(unsigned long*)(&(dataRange->MajorFormat))));+        /* Check that subformat is WAVEFORMATEX, PCM or WILDCARD */+        if( IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat) ||+            IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||+            IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) ||+            IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_WILDCARD) ||+            IsEqualGUID(&dataRange->MajorFormat, &KSDATAFORMAT_TYPE_AUDIO) )+        {+            int defaultIndex;+            result = paNoError;+            /* Record the maximum possible channels with this pin */+            if( ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels == (ULONG) -1 )+            {+                pin->maxChannels = MAXIMUM_NUMBER_OF_CHANNELS;+            }+            else if( (int) ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels > pin->maxChannels )+            {+                pin->maxChannels = (int) ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels;+            }+            PA_DEBUG(("PinNew: MaxChannel: %d\n",pin->maxChannels));++            /* Record the formats (bit depths) that are supported */+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 8) )+            {+                pin->formats |= paInt8;+                PA_DEBUG(("PinNew: Format PCM 8 bit supported\n"));+            }+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 16) )+            {+                pin->formats |= paInt16;+                PA_DEBUG(("PinNew: Format PCM 16 bit supported\n"));+            }+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 24) )+            {+                pin->formats |= paInt24;+                PA_DEBUG(("PinNew: Format PCM 24 bit supported\n"));+            }+            if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 32) )+            {+                if (IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))+                {+                    pin->formats |= paFloat32;+                    PA_DEBUG(("PinNew: Format IEEE float 32 bit supported\n"));+                }+                else+                {+                    pin->formats |= paInt32;+                    PA_DEBUG(("PinNew: Format PCM 32 bit supported\n"));+                }+            }++            defaultIndex = DefaultSampleFrequencyIndex((KSDATARANGE_AUDIO*)dataRange);+            if (defaultIndex >= 0 && defaultIndex < defaultSampleRateIndex)+            {+                defaultSampleRateIndex = defaultIndex;+            }+        }+        dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize);+    }++    if( result != paNoError )+        goto error;++    /* If none of the frequencies searched for are present, there's something seriously wrong */+    if (defaultSampleRateIndex == defaultSampleRateSearchOrderCount)+    {+        PA_DEBUG(("PinNew: No default sample rate found, skipping pin!\n"));+        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "PinNew: No default sample rate found");+        result = paUnanticipatedHostError;+        goto error;+    }++    /* Set the default sample rate */+    pin->defaultSampleRate = defaultSampleRateSearchOrder[defaultSampleRateIndex];+    PA_DEBUG(("PinNew: Default sample rate = %d Hz\n", pin->defaultSampleRate));++    /* Get instance information */+    result = WdmGetPinPropertySimple(+        parentFilter->handle,+        pinId,+        &KSPROPSETID_Pin,+        KSPROPERTY_PIN_CINSTANCES,+        &pin->instances,+        sizeof(KSPIN_CINSTANCES),+        NULL);++    if( result != paNoError )+        goto error;++    /* If WaveRT, check if pin supports notification mode */+    if (parentFilter->devInfo.streamingType == Type_kWaveRT)+    {+        BOOL bSupportsNotification = FALSE;+        if (PinQueryNotificationSupport(pin, &bSupportsNotification) == paNoError)+        {+            pin->pinKsSubType = bSupportsNotification ? SubType_kNotification : SubType_kPolled;+        }+    }++    /* Query pin name (which means we need to traverse to non IRP pin, via physical connection to topology filter pin, through+    its nodes to the endpoint pin, and get that ones name... phew...) */+    PA_DEBUG(("PinNew: Finding topology pin...\n"));++    {+        ULONG topoPinId = GetConnectedPin(pinId, (pin->dataFlow == KSPIN_DATAFLOW_IN), parentFilter, -1, NULL, NULL);+        const wchar_t kInputName[] = L"Input";+        const wchar_t kOutputName[] = L"Output";++        if (topoPinId != KSFILTER_NODE)+        {+            /* Get physical connection for topo pin */+            unsigned long cbBytes = 0;+            PA_DEBUG(("PinNew: Getting physical connection...\n"));+            result = WdmGetPinPropertySimple(parentFilter->handle,+                topoPinId,+                &KSPROPSETID_Pin,+                KSPROPERTY_PIN_PHYSICALCONNECTION,+                0,+                0,+                &cbBytes+                );++            if (result != paNoError)+            {+                /* No physical connection -> there is no topology filter! So we get the name of the pin! */+                PA_DEBUG(("PinNew: No physical connection! Getting the pin name\n"));+                result = WdmGetPinPropertySimple(parentFilter->handle,+                    topoPinId,+                    &KSPROPSETID_Pin,+                    KSPROPERTY_PIN_NAME,+                    pin->friendlyName,+                    MAX_PATH,+                    NULL);+                if (result != paNoError)+                {+                    GUID category = {0};++                    /* Get pin category information */+                    result = WdmGetPinPropertySimple(parentFilter->handle,+                        topoPinId,+                        &KSPROPSETID_Pin,+                        KSPROPERTY_PIN_CATEGORY,+                        &category,+                        sizeof(GUID),+                        NULL);++                    if (result == paNoError)+                    {+                        result = GetNameFromCategory(&category, (pin->dataFlow == KSPIN_DATAFLOW_OUT), pin->friendlyName, MAX_PATH);+                    }+                }++                /* Make sure pin gets a name here... */+                if (wcslen(pin->friendlyName) == 0)+                {+                    wcscpy(pin->friendlyName, (pin->dataFlow == KSPIN_DATAFLOW_IN) ? kOutputName : kInputName);+#ifdef UNICODE+                    PA_DEBUG(("PinNew: Setting pin friendly name to '%s'\n", pin->friendlyName));+#else+                    PA_DEBUG(("PinNew: Setting pin friendly name to '%S'\n", pin->friendlyName));+#endif+                }++                /* This is then == the endpoint pin */+                pin->endpointPinId = (pin->dataFlow == KSPIN_DATAFLOW_IN) ? pinId : topoPinId;+            }+            else+            {+                KSPIN_PHYSICALCONNECTION* pc = (KSPIN_PHYSICALCONNECTION*)PaUtil_AllocateMemory(cbBytes + 2);+                PA_DEBUG(("PinNew: Physical connection found!\n"));+                if (pc == NULL)+                {+                    result = paInsufficientMemory;+                    goto error;+                }+                result = WdmGetPinPropertySimple(parentFilter->handle,+                    topoPinId,+                    &KSPROPSETID_Pin,+                    KSPROPERTY_PIN_PHYSICALCONNECTION,+                    pc,+                    cbBytes,+                    NULL+                    );+                if (result == paNoError)+                {+                    wchar_t symbLinkName[MAX_PATH];+                    wcsncpy(symbLinkName, pc->SymbolicLinkName, MAX_PATH);+                    if (symbLinkName[1] == TEXT('?'))+                    {+                        symbLinkName[1] = TEXT('\\');+                    }++                    if (pin->parentFilter->topologyFilter == NULL)+                    {+                        PA_DEBUG(("PinNew: Creating topology filter '%S'\n", symbLinkName));++                        pin->parentFilter->topologyFilter = FilterNew(Type_kNotUsed, 0, symbLinkName, L"", &result);+                        if (pin->parentFilter->topologyFilter == NULL)+                        {+                            PA_DEBUG(("PinNew: Failed creating topology filter\n"));+                            result = paUnanticipatedHostError;+                            PaWinWDM_SetLastErrorInfo(result, "Failed to create topology filter '%S'", symbLinkName);+                            goto error;+                        }++                        /* Copy info so we have it in device info */+                        wcsncpy(pin->parentFilter->devInfo.topologyPath, symbLinkName, MAX_PATH);+                    }+                    else+                    {+                        /* Must be the same */+                        assert(wcscmp(symbLinkName, pin->parentFilter->topologyFilter->devInfo.filterPath) == 0);+                    }++                    PA_DEBUG(("PinNew: Opening topology filter..."));++                    result = FilterUse(pin->parentFilter->topologyFilter);+                    if (result == paNoError)+                    {+                        unsigned long endpointPinId;++                        if (pin->dataFlow == KSPIN_DATAFLOW_IN)+                        {+                            /* The "endpointPinId" is what WASAPI looks at for pin names */+                            GUID category = {0};++                            PA_DEBUG(("PinNew: Checking for output endpoint pin id...\n"));++                            endpointPinId = GetConnectedPin(pc->Pin, TRUE, pin->parentFilter->topologyFilter, -1, NULL, NULL);++                            if (endpointPinId == KSFILTER_NODE)+                            {+                                result = paUnanticipatedHostError;+                                PaWinWDM_SetLastErrorInfo(result, "Failed to get endpoint pin ID on topology filter!");+                                goto error;+                            }++                            PA_DEBUG(("PinNew: Found endpoint pin id %u\n", endpointPinId));++                            /* Get pin category information */+                            result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,+                                endpointPinId,+                                &KSPROPSETID_Pin,+                                KSPROPERTY_PIN_CATEGORY,+                                &category,+                                sizeof(GUID),+                                NULL);++                            if (result == paNoError)+                            {+#if !PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES+                                wchar_t pinName[MAX_PATH];++                                PA_DEBUG(("PinNew: Getting pin name property..."));++                                /* Ok, try pin name also, and favor that if available */+                                result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,+                                    endpointPinId,+                                    &KSPROPSETID_Pin,+                                    KSPROPERTY_PIN_NAME,+                                    pinName,+                                    MAX_PATH,+                                    NULL);++                                if (result == paNoError && wcslen(pinName)>0)+                                {+                                    wcsncpy(pin->friendlyName, pinName, MAX_PATH);+                                }+                                else+#endif+                                {+                                    result = GetNameFromCategory(&category, (pin->dataFlow == KSPIN_DATAFLOW_OUT), pin->friendlyName, MAX_PATH);+                                }++                                if (wcslen(pin->friendlyName) == 0)+                                {+                                    wcscpy(pin->friendlyName, L"Output");+                                }+#ifdef UNICODE+                                PA_DEBUG(("PinNew: Pin name '%s'\n", pin->friendlyName));+#else+                                PA_DEBUG(("PinNew: Pin name '%S'\n", pin->friendlyName));+#endif                                +                            }++                            /* Set endpoint pin ID (this is the topology INPUT pin, since portmixer will always traverse the+                            filter in audio streaming direction, see http://msdn.microsoft.com/en-us/library/windows/hardware/ff536331(v=vs.85).aspx+                            for more information)+                            */+                            pin->endpointPinId = pc->Pin;+                        }+                        else+                        {+                            unsigned muxCount = 0;+                            int muxPos = 0;+                            /* Max 64 multiplexer inputs... sanity check :) */+                            for (i = 0; i < 64; ++i)+                            {+                                ULONG muxNodeIdTest = (unsigned)-1;+                                PA_DEBUG(("PinNew: Checking for input endpoint pin id (%d)...\n", i));++                                endpointPinId = GetConnectedPin(pc->Pin,+                                    FALSE,+                                    pin->parentFilter->topologyFilter,+                                    (int)i,+                                    NULL,+                                    &muxNodeIdTest);+++                                if (endpointPinId == KSFILTER_NODE)+                                {+                                    /* We're done */+                                    PA_DEBUG(("PinNew: Done with inputs.\n", endpointPinId));+                                    break;+                                }+                                else+                                {+                                    /* The "endpointPinId" is what WASAPI looks at for pin names */+                                    GUID category = {0};++                                    PA_DEBUG(("PinNew: Found endpoint pin id %u\n", endpointPinId));++                                    /* Get pin category information */+                                    result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,+                                        endpointPinId,+                                        &KSPROPSETID_Pin,+                                        KSPROPERTY_PIN_CATEGORY,+                                        &category,+                                        sizeof(GUID),+                                        NULL);++                                    if (result == paNoError)+                                    {+                                        if (muxNodeIdTest == (unsigned)-1)+                                        {+                                            /* Ok, try pin name, and favor that if available */+                                            result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,+                                                endpointPinId,+                                                &KSPROPSETID_Pin,+                                                KSPROPERTY_PIN_NAME,+                                                pin->friendlyName,+                                                MAX_PATH,+                                                NULL);++                                            if (result != paNoError)+                                            {+                                                result = GetNameFromCategory(&category, TRUE, pin->friendlyName, MAX_PATH);+                                            }+                                            break;+                                        }+                                        else+                                        {+                                            result = GetNameFromCategory(&category, TRUE, NULL, 0);++                                            if (result == paNoError)+                                            {+                                                ++muxCount;+                                            }+                                        }+                                    }+                                    else+                                    {+                                        PA_DEBUG(("PinNew: Failed to get pin category"));+                                    }+                                }+                            }++                            if (muxCount == 0)+                            {+                                pin->endpointPinId = endpointPinId;+                                /* Make sure we get a name for the pin */+                                if (wcslen(pin->friendlyName) == 0)+                                {+                                    wcscpy(pin->friendlyName, kInputName);+                                }+#ifdef UNICODE+                                PA_DEBUG(("PinNew: Input friendly name '%s'\n", pin->friendlyName));+#else+                                PA_DEBUG(("PinNew: Input friendly name '%S'\n", pin->friendlyName));+#endif+                            }+                            else // muxCount > 0+                            {+                                PA_DEBUG(("PinNew: Setting up %u inputs\n", muxCount));++                                /* Now we redo the operation once known how many multiplexer positions there are */+                                pin->inputs = (PaWinWdmMuxedInput**)PaUtil_AllocateMemory(muxCount * sizeof(PaWinWdmMuxedInput*));+                                if (pin->inputs == NULL)+                                {+                                    FilterRelease(pin->parentFilter->topologyFilter);+                                    result = paInsufficientMemory;+                                    goto error;+                                }+                                pin->inputCount = muxCount;++                                for (i = 0; i < muxCount; ++muxPos)+                                {+                                    PA_DEBUG(("PinNew: Setting up input %u...\n", i));++                                    if (pin->inputs[i] == NULL)+                                    {+                                        pin->inputs[i] = (PaWinWdmMuxedInput*)PaUtil_AllocateMemory(sizeof(PaWinWdmMuxedInput));+                                        if (pin->inputs[i] == NULL)+                                        {+                                            FilterRelease(pin->parentFilter->topologyFilter);+                                            result = paInsufficientMemory;+                                            goto error;+                                        }+                                    }++                                    endpointPinId = GetConnectedPin(pc->Pin,+                                        FALSE,+                                        pin->parentFilter->topologyFilter,+                                        muxPos,+                                        &pin->inputs[i]->muxPinId, +                                        &pin->inputs[i]->muxNodeId);++                                    if (endpointPinId != KSFILTER_NODE)+                                    {+                                        /* The "endpointPinId" is what WASAPI looks at for pin names */+                                        GUID category = {0};++                                        /* Set input endpoint ID */+                                        pin->inputs[i]->endpointPinId = endpointPinId;++                                        /* Get pin category information */+                                        result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,+                                            endpointPinId,+                                            &KSPROPSETID_Pin,+                                            KSPROPERTY_PIN_CATEGORY,+                                            &category,+                                            sizeof(GUID),+                                            NULL);++                                        if (result == paNoError)+                                        {+                                            /* Try pin name first, and if that is not defined, use category instead */+                                            result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,+                                                endpointPinId,+                                                &KSPROPSETID_Pin,+                                                KSPROPERTY_PIN_NAME,+                                                pin->inputs[i]->friendlyName,+                                                MAX_PATH,+                                                NULL);++                                            if (result != paNoError)+                                            {+                                                result = GetNameFromCategory(&category, TRUE, pin->inputs[i]->friendlyName, MAX_PATH);+                                                if (result != paNoError)+                                                {+                                                    /* Only specify name, let name hash in ScanDeviceInfos fix postfix enumerators */+                                                    wcscpy(pin->inputs[i]->friendlyName, kInputName);+                                                }+                                            }+#ifdef UNICODE+                                            PA_DEBUG(("PinNew: Input (%u) friendly name '%s'\n", i, pin->inputs[i]->friendlyName));+#else+                                            PA_DEBUG(("PinNew: Input (%u) friendly name '%S'\n", i, pin->inputs[i]->friendlyName));+#endif+                                            ++i;+                                        }+                                    }+                                    else+                                    {+                                        /* Should never come here! */+                                        assert(FALSE);+                                    }+                                }+                            }+                        }+                    }+                }+                PaUtil_FreeMemory(pc);+            }+        }+        else+        {+            PA_DEBUG(("PinNew: No topology pin id found. Bad...\n"));+            /* No TOPO pin id ??? This is bad. Ok, so we just say it is an input or output... */+            wcscpy(pin->friendlyName, (pin->dataFlow == KSPIN_DATAFLOW_IN) ? kOutputName : kInputName);+        }+    }++    /* Release topology filter if it has been used */+    if (pin->parentFilter->topologyFilter && pin->parentFilter->topologyFilter->handle != NULL)+    {+        PA_DEBUG(("PinNew: Releasing topology filter...\n"));+        FilterRelease(pin->parentFilter->topologyFilter);+    }++    /* Success */+    *error = paNoError;+    PA_DEBUG(("Pin created successfully\n"));+    PA_LOGL_;+    return pin;++error:+    PA_DEBUG(("PinNew: Error %d\n", result));+    /*+    Error cleanup+    */++    PaUtil_FreeMemory( item );+    if( pin )+    {+        if (pin->parentFilter->topologyFilter && pin->parentFilter->topologyFilter->handle != NULL)+        {+            FilterRelease(pin->parentFilter->topologyFilter);+        }++        PaUtil_FreeMemory( pin->pinConnect );+        PaUtil_FreeMemory( pin->dataRangesItem );+        PaUtil_FreeMemory( pin );+    }+    *error = result;+    PA_LOGL_;+    return NULL;+}++/*+Safely free all resources associated with the pin+*/+static void PinFree(PaWinWdmPin* pin)+{+    unsigned i;+    PA_LOGE_;+    if( pin )+    {+        PinClose(pin);+        if( pin->pinConnect )+        {+            PaUtil_FreeMemory( pin->pinConnect );+        }+        if( pin->dataRangesItem )+        {+            PaUtil_FreeMemory( pin->dataRangesItem );+        }+        if( pin->inputs )+        {+            for (i = 0; i < pin->inputCount; ++i)+            {+                PaUtil_FreeMemory( pin->inputs[i] );+            }+            PaUtil_FreeMemory( pin->inputs );+        }+        PaUtil_FreeMemory( pin );+    }+    PA_LOGL_;+}++/*+If the pin handle is open, close it+*/+static void PinClose(PaWinWdmPin* pin)+{+    PA_LOGE_;+    if( pin == NULL )+    {+        PA_DEBUG(("Closing NULL pin!"));+        PA_LOGL_;+        return;+    }+    if( pin->handle != NULL )+    {+        PinSetState( pin, KSSTATE_PAUSE );+        PinSetState( pin, KSSTATE_STOP );+        CloseHandle( pin->handle );+        pin->handle = NULL;+        FilterRelease(pin->parentFilter);+    }+    PA_LOGL_;+}++/*+Set the state of this (instantiated) pin+*/+static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state)+{+    PaError result = paNoError;+    KSPROPERTY prop;++    PA_LOGE_;+    prop.Set = KSPROPSETID_Connection;+    prop.Id  = KSPROPERTY_CONNECTION_STATE;+    prop.Flags = KSPROPERTY_TYPE_SET;++    if( pin == NULL )+        return paInternalError;+    if( pin->handle == NULL )+        return paInternalError;++    result = WdmSyncIoctl(pin->handle, IOCTL_KS_PROPERTY, &prop, sizeof(KSPROPERTY), &state, sizeof(KSSTATE), NULL);++    PA_LOGL_;+    return result;+}++static PaError PinInstantiate(PaWinWdmPin* pin)+{+    PaError result;+    unsigned long createResult;+    KSALLOCATOR_FRAMING ksaf;+    KSALLOCATOR_FRAMING_EX ksafex;++    PA_LOGE_;++    if( pin == NULL )+        return paInternalError;+    if(!pin->pinConnect)+        return paInternalError;++    FilterUse(pin->parentFilter);++    createResult = FunctionKsCreatePin(+        pin->parentFilter->handle,+        pin->pinConnect,+        GENERIC_WRITE | GENERIC_READ,+        &pin->handle+        );++    PA_DEBUG(("Pin create result = 0x%08x\n",createResult));+    if( createResult != ERROR_SUCCESS )+    {+        FilterRelease(pin->parentFilter);+        pin->handle = NULL;+        switch (createResult)+        {+        case ERROR_INVALID_PARAMETER:+            /* First case when pin actually don't support the format */+            return paSampleFormatNotSupported;+        case ERROR_BAD_COMMAND:+            /* Case when pin is occupied (by another application) */+            return paDeviceUnavailable;+        default:+            /* All other cases */+            return paInvalidDevice;+        }+    }++    if (pin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)+    {+        /* Framing size query only valid for WaveCyclic devices */+        result = WdmGetPropertySimple(+            pin->handle,+            &KSPROPSETID_Connection,+            KSPROPERTY_CONNECTION_ALLOCATORFRAMING,+            &ksaf,+            sizeof(ksaf));++        if( result != paNoError )+        {+            result = WdmGetPropertySimple(+                pin->handle,+                &KSPROPSETID_Connection,+                KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,+                &ksafex,+                sizeof(ksafex));+            if( result == paNoError )+            {+                pin->frameSize = ksafex.FramingItem[0].FramingRange.Range.MinFrameSize;+            }+        }+        else+        {+            pin->frameSize = ksaf.FrameSize;+        }+    }++    PA_LOGL_;++    return paNoError;+}++static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format)+{+    unsigned long size;+    void* newConnect;++    PA_LOGE_;++    if( pin == NULL )+        return paInternalError;+    if( format == NULL )+        return paInternalError;++    size = GetWfexSize(format) + sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX) - sizeof(WAVEFORMATEX);++    if( pin->pinConnectSize != size )+    {+        newConnect = PaUtil_AllocateMemory( size );+        if( newConnect == NULL )+            return paInsufficientMemory;+        memcpy( newConnect, (void*)pin->pinConnect, min(pin->pinConnectSize,size) );+        PaUtil_FreeMemory( pin->pinConnect );+        pin->pinConnect = (KSPIN_CONNECT*)newConnect;+        pin->pinConnectSize = size;+        pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)((KSPIN_CONNECT*)newConnect + 1);+        pin->ksDataFormatWfx->DataFormat.FormatSize = size - sizeof(KSPIN_CONNECT);+    }++    memcpy( (void*)&(pin->ksDataFormatWfx->WaveFormatEx), format, GetWfexSize(format) );+    pin->ksDataFormatWfx->DataFormat.SampleSize = (unsigned short)(format->nChannels * (format->wBitsPerSample / 8));++    PA_LOGL_;++    return paNoError;+}++static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format)+{+    KSDATARANGE_AUDIO* dataRange;+    unsigned long count;+    GUID guid = DYNAMIC_GUID( DEFINE_WAVEFORMATEX_GUID(format->wFormatTag) );+    PaError result = paInvalidDevice;+    const WAVEFORMATEXTENSIBLE* pFormatExt = (format->wFormatTag == WAVE_FORMAT_EXTENSIBLE) ? (const WAVEFORMATEXTENSIBLE*)format : 0;++    PA_LOGE_;++    if( pFormatExt != 0 )+    {+        guid = pFormatExt->SubFormat;+    }+    dataRange = (KSDATARANGE_AUDIO*)pin->dataRanges;+    for(count = 0;+        count<pin->dataRangesItem->Count;+        count++, +        dataRange = (KSDATARANGE_AUDIO*)( ((char*)dataRange) + dataRange->DataRange.FormatSize)) /* Need to update dataRange here, due to 'continue' !! */+    {+        /* Check major format*/+        if (!(IsEqualGUID(&(dataRange->DataRange.MajorFormat), &KSDATAFORMAT_TYPE_AUDIO) ||+            IsEqualGUID(&(dataRange->DataRange.MajorFormat), &KSDATAFORMAT_TYPE_WILDCARD)))+        {+            continue;+        }++        /* This is an audio or wildcard datarange... */+        if (! (IsEqualGUID(&(dataRange->DataRange.SubFormat), &KSDATAFORMAT_SUBTYPE_WILDCARD) ||+            IsEqualGUID(&(dataRange->DataRange.SubFormat), &KSDATAFORMAT_SUBTYPE_PCM) ||+            IsEqualGUID(&(dataRange->DataRange.SubFormat), &guid) ))+        {+            continue;+        }++        /* Check specifier... */+        if (! (IsEqualGUID(&(dataRange->DataRange.Specifier), &KSDATAFORMAT_SPECIFIER_WILDCARD) ||+            IsEqualGUID(&(dataRange->DataRange.Specifier), &KSDATAFORMAT_SPECIFIER_WAVEFORMATEX)) )+        {+            continue;+        }++        PA_DEBUG(("Pin:%x, DataRange:%d\n",(void*)pin,count));+        PA_DEBUG(("\tFormatSize:%d, SampleSize:%d\n",dataRange->DataRange.FormatSize,dataRange->DataRange.SampleSize));+        PA_DEBUG(("\tMaxChannels:%d\n",dataRange->MaximumChannels));+        PA_DEBUG(("\tBits:%d-%d\n",dataRange->MinimumBitsPerSample,dataRange->MaximumBitsPerSample));+        PA_DEBUG(("\tSampleRate:%d-%d\n",dataRange->MinimumSampleFrequency,dataRange->MaximumSampleFrequency));++        if( dataRange->MaximumChannels != (ULONG)-1 && +            dataRange->MaximumChannels < format->nChannels )+        {+            result = paInvalidChannelCount;+            continue;+        }++        if (pFormatExt != 0)+        {+            if ( dataRange->MinimumBitsPerSample > pFormatExt->Samples.wValidBitsPerSample )+            {+                result = paSampleFormatNotSupported;+                continue;+            }+            if ( dataRange->MaximumBitsPerSample < pFormatExt->Samples.wValidBitsPerSample )+            {+                result = paSampleFormatNotSupported;+                continue;+            }+        }+        else+        {+            if( dataRange->MinimumBitsPerSample > format->wBitsPerSample )+            {+                result = paSampleFormatNotSupported;+                continue;+            }++            if( dataRange->MaximumBitsPerSample < format->wBitsPerSample )+            {+                result = paSampleFormatNotSupported;+                continue;+            }+        }++        if( dataRange->MinimumSampleFrequency > format->nSamplesPerSec )+        {+            result = paInvalidSampleRate;+            continue;+        }++        if( dataRange->MaximumSampleFrequency < format->nSamplesPerSec )+        {+            result = paInvalidSampleRate;+            continue;+        }++        /* Success! */+        result = paNoError;+        break;+    }++    PA_LOGL_;+    return result;+}++static PaError PinQueryNotificationSupport(PaWinWdmPin* pPin, BOOL* pbResult)+{+    PaError result = paNoError;+    KSPROPERTY propIn;++    propIn.Set = KSPROPSETID_RtAudio;+    propIn.Id = 8; /* = KSPROPERTY_RTAUDIO_QUERY_NOTIFICATION_SUPPORT */+    propIn.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,+        &propIn,+        sizeof(KSPROPERTY),+        pbResult,+        sizeof(BOOL),+        NULL);++    if (result != paNoError) +    {+        PA_DEBUG(("Failed PinQueryNotificationSupport\n"));+    }++    return result;++}++static PaError PinGetBufferWithNotification(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)+{+    PaError result = paNoError;+    KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION propIn;+    KSRTAUDIO_BUFFER propOut;++    propIn.BaseAddress = 0;+    propIn.NotificationCount = 2;+    propIn.RequestedBufferSize = *pRequestedBufSize;+    propIn.Property.Set = KSPROPSETID_RtAudio;+    propIn.Property.Id = KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION;+    propIn.Property.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,+        &propIn,+        sizeof(KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION),+        &propOut,+        sizeof(KSRTAUDIO_BUFFER),+        NULL);++    if (result == paNoError) +    {+        *pBuffer = propOut.BufferAddress;+        *pRequestedBufSize = propOut.ActualBufferSize;+        *pbCallMemBarrier = propOut.CallMemoryBarrier;+    }+    else +    {+        PA_DEBUG(("Failed to get buffer with notification\n"));+    }++    return result;+}++static PaError PinGetBufferWithoutNotification(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)+{+    PaError result = paNoError;+    KSRTAUDIO_BUFFER_PROPERTY propIn;+    KSRTAUDIO_BUFFER propOut;++    propIn.BaseAddress = NULL;+    propIn.RequestedBufferSize = *pRequestedBufSize;+    propIn.Property.Set = KSPROPSETID_RtAudio;+    propIn.Property.Id = KSPROPERTY_RTAUDIO_BUFFER;+    propIn.Property.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,+        &propIn,+        sizeof(KSRTAUDIO_BUFFER_PROPERTY),+        &propOut,+        sizeof(KSRTAUDIO_BUFFER),+        NULL);++    if (result == paNoError)+    {+        *pBuffer = propOut.BufferAddress;+        *pRequestedBufSize = propOut.ActualBufferSize;+        *pbCallMemBarrier = propOut.CallMemoryBarrier;+    }+    else +    {+        PA_DEBUG(("Failed to get buffer without notification\n"));+    }++    return result;+}++/* greatest common divisor - PGCD in French */+static unsigned long PaWinWDMGCD( unsigned long a, unsigned long b )+{+    return (b==0) ? a : PaWinWDMGCD( b, a%b);+}+++/* This function will handle getting the cyclic buffer from a WaveRT driver. Certain WaveRT drivers needs to have+requested buffer size on multiples of 128 bytes:++*/+static PaError PinGetBuffer(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)+{+    PaError result = paNoError;++    while (1)+    {+        if (pPin->pinKsSubType != SubType_kPolled)+        {+            /* In case of unknown (or notification), we try both modes */+            result = PinGetBufferWithNotification(pPin, pBuffer, pRequestedBufSize, pbCallMemBarrier);+            if (result == paNoError)+            {+                PA_DEBUG(("PinGetBuffer: SubType_kNotification\n"));+                pPin->pinKsSubType = SubType_kNotification;+                break;+            }+        }++        result = PinGetBufferWithoutNotification(pPin, pBuffer, pRequestedBufSize, pbCallMemBarrier);+        if (result == paNoError)+        {+            PA_DEBUG(("PinGetBuffer: SubType_kPolled\n"));+            pPin->pinKsSubType = SubType_kPolled;+            break;+        }++        /* Check if requested size is on a 128 byte boundary */+        if (((*pRequestedBufSize) % 128UL) == 0)+        {+            PA_DEBUG(("Buffer size on 128 byte boundary, still fails :(\n"));+            /* Ok, can't do much more */+            break;+        }+        else+        {+            /* Compute LCM so we know which sizes are on a 128 byte boundary */+            const unsigned gcd = PaWinWDMGCD(128UL, pPin->ksDataFormatWfx->WaveFormatEx.nBlockAlign);+            const unsigned lcm = (128UL * pPin->ksDataFormatWfx->WaveFormatEx.nBlockAlign) / gcd;+            DWORD dwOldSize = *pRequestedBufSize;++            /* Align size to (next larger) LCM byte boundary, and then we try again. Note that LCM is not necessarily a+            power of 2. */+            *pRequestedBufSize = ((*pRequestedBufSize + lcm - 1) / lcm) * lcm;++            PA_DEBUG(("Adjusting buffer size from %u to %u bytes (128 byte boundary, LCM=%u)\n", dwOldSize, *pRequestedBufSize, lcm));+        }+    }++    return result;+}++static PaError PinRegisterPositionRegister(PaWinWdmPin* pPin) +{+    PaError result = paNoError;+    KSRTAUDIO_HWREGISTER_PROPERTY propIn;+    KSRTAUDIO_HWREGISTER propOut;++    PA_LOGE_;++    propIn.BaseAddress = NULL;+    propIn.Property.Set = KSPROPSETID_RtAudio;+    propIn.Property.Id = KSPROPERTY_RTAUDIO_POSITIONREGISTER;+    propIn.Property.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,+        &propIn,+        sizeof(KSRTAUDIO_HWREGISTER_PROPERTY),+        &propOut,+        sizeof(KSRTAUDIO_HWREGISTER),+        NULL);++    if (result == paNoError) +    {+        pPin->positionRegister = (ULONG*)propOut.Register;+    }+    else+    {+        PA_DEBUG(("Failed to register position register\n"));+    }++    PA_LOGL_;++    return result;+}++static PaError PinRegisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle) +{+    PaError result = paNoError;+    KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY prop;++    PA_LOGE_;++    prop.NotificationEvent = handle;+    prop.Property.Set = KSPROPSETID_RtAudio;+    prop.Property.Id = KSPROPERTY_RTAUDIO_REGISTER_NOTIFICATION_EVENT;+    prop.Property.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(pPin->handle,+        IOCTL_KS_PROPERTY,+        &prop,+        sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),+        &prop,+        sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),+        NULL);++    if (result != paNoError) {+        PA_DEBUG(("Failed to register notification handle 0x%08X\n", handle));+    }++    PA_LOGL_;++    return result;+}++static PaError PinUnregisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle) +{+    PaError result = paNoError;+    KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY prop;++    PA_LOGE_;++    if (handle != NULL)+    {+        prop.NotificationEvent = handle;+        prop.Property.Set = KSPROPSETID_RtAudio;+        prop.Property.Id = KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT;+        prop.Property.Flags = KSPROPERTY_TYPE_GET;++        result = WdmSyncIoctl(pPin->handle,+            IOCTL_KS_PROPERTY,+            &prop,+            sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),+            &prop,+            sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),+            NULL);++        if (result != paNoError) {+            PA_DEBUG(("Failed to unregister notification handle 0x%08X\n", handle));+        }+    }+    PA_LOGL_;++    return result;+}++static PaError PinGetHwLatency(PaWinWdmPin* pPin, ULONG* pFifoSize, ULONG* pChipsetDelay, ULONG* pCodecDelay)+{+    PaError result = paNoError;+    KSPROPERTY propIn;+    KSRTAUDIO_HWLATENCY propOut;++    PA_LOGE_;++    propIn.Set = KSPROPSETID_RtAudio;+    propIn.Id = KSPROPERTY_RTAUDIO_HWLATENCY;+    propIn.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,+        &propIn,+        sizeof(KSPROPERTY),+        &propOut,+        sizeof(KSRTAUDIO_HWLATENCY),+        NULL);++    if (result == paNoError)+    {+        *pFifoSize = propOut.FifoSize;+        *pChipsetDelay = propOut.ChipsetDelay;+        *pCodecDelay = propOut.CodecDelay;+    }+    else+    {+        PA_DEBUG(("Failed to retrieve hardware FIFO size!\n"));+    }++    PA_LOGL_;++    return result;+}++/* This one is used for WaveRT */+static PaError PinGetAudioPositionDirect(PaWinWdmPin* pPin, ULONG* pPosition)+{+    *pPosition = (*pPin->positionRegister);+    return paNoError;+}++/* This one also, but in case the driver hasn't implemented memory mapped access to the position register */+static PaError PinGetAudioPositionViaIOCTL(PaWinWdmPin* pPin, ULONG* pPosition)+{+    PaError result = paNoError;+    KSPROPERTY propIn;+    KSAUDIO_POSITION propOut;++    PA_LOGE_;++    propIn.Set = KSPROPSETID_Audio;+    propIn.Id = KSPROPERTY_AUDIO_POSITION;+    propIn.Flags = KSPROPERTY_TYPE_GET;++    result = WdmSyncIoctl(pPin->handle,+        IOCTL_KS_PROPERTY,+        &propIn, sizeof(KSPROPERTY),+        &propOut, sizeof(KSAUDIO_POSITION),+        NULL);++    if (result == paNoError)+    {+        *pPosition = (ULONG)(propOut.PlayOffset);+    }+    else+    {+        PA_DEBUG(("Failed to get audio position!\n"));+    }++    PA_LOGL_;++    return result;++}++/***********************************************************************************************/++/**+* Create a new filter object. +*/+static PaWinWdmFilter* FilterNew( PaWDMKSType type, DWORD devNode, const wchar_t* filterName, const wchar_t* friendlyName, PaError* error )+{+    PaWinWdmFilter* filter = 0;+    PaError result;++    /* Allocate the new filter object */+    filter = (PaWinWdmFilter*)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter) );+    if( !filter )+    {+        result = paInsufficientMemory;+        goto error;+    }++    PA_DEBUG(("FilterNew: Creating filter '%S'\n", friendlyName));++    /* Set type flag */+    filter->devInfo.streamingType = type;++    /* Store device node */+    filter->deviceNode = devNode;++    /* Zero the filter object - done by AllocateMemory */+    /* memset( (void*)filter, 0, sizeof(PaWinWdmFilter) ); */++    /* Copy the filter name */+    wcsncpy(filter->devInfo.filterPath, filterName, MAX_PATH);++    /* Copy the friendly name */+    wcsncpy(filter->friendlyName, friendlyName, MAX_PATH);++    PA_DEBUG(("FilterNew: Opening filter...\n", friendlyName));++    /* Open the filter handle */+    result = FilterUse(filter);+    if( result != paNoError )+    {+        goto error;+    }++    /* Get pin count */+    result = WdmGetPinPropertySimple+        (+        filter->handle,+        0,+        &KSPROPSETID_Pin,+        KSPROPERTY_PIN_CTYPES,+        &filter->pinCount,+        sizeof(filter->pinCount),+        NULL);++    if( result != paNoError)+    {+        goto error;+    }++    /* Get connections & nodes for filter */+    result = WdmGetPropertyMulti(+        filter->handle,+        &KSPROPSETID_Topology,+        KSPROPERTY_TOPOLOGY_CONNECTIONS,+        &filter->connections);++    if( result != paNoError)+    {+        goto error;+    }++    result = WdmGetPropertyMulti(+        filter->handle,+        &KSPROPSETID_Topology,+        KSPROPERTY_TOPOLOGY_NODES,+        &filter->nodes);++    if( result != paNoError)+    {+        goto error;+    }++    /* For debugging purposes */+    DumpConnectionsAndNodes(filter);++    /* Get product GUID (it might not be supported) */+    {+        KSCOMPONENTID compId;+        if (WdmGetPropertySimple(filter->handle, &KSPROPSETID_General, KSPROPERTY_GENERAL_COMPONENTID, &compId, sizeof(KSCOMPONENTID)) == paNoError)+        {+            filter->devInfo.deviceProductGuid = compId.Product;+        }+    }++    /* This section is not executed for topology filters */+    if (type != Type_kNotUsed)+    {+        /* Initialize the pins */+        result = FilterInitializePins(filter);++        if( result != paNoError)+        {+            goto error;+        }+    }++    /* Close the filter handle for now+    * It will be opened later when needed */+    FilterRelease(filter);++    *error = paNoError;+    return filter;++error:+    PA_DEBUG(("FilterNew: Error %d\n", result));+    /*+    Error cleanup+    */+    FilterFree(filter);++    *error = result;+    return NULL;+}++/**+* Add reference to filter+*/+static void FilterAddRef( PaWinWdmFilter* filter )+{+    if (filter != 0)+    {+        filter->filterRefCount++;+    }+}+++/**+* Initialize the pins of the filter. This is separated from FilterNew because this might fail if there is another+* process using the pin(s).+*/+PaError FilterInitializePins( PaWinWdmFilter* filter )+{+    PaError result = paNoError;+    int pinId;++    if (filter->devInfo.streamingType == Type_kNotUsed)+        return paNoError;++    if (filter->pins != NULL)+        return paNoError;   ++    /* Allocate pointer array to hold the pins */+    filter->pins = (PaWinWdmPin**)PaUtil_AllocateMemory( sizeof(PaWinWdmPin*) * filter->pinCount );+    if( !filter->pins )+    {+        result = paInsufficientMemory;+        goto error;+    }++    /* Create all the pins we can */+    for(pinId = 0; pinId < filter->pinCount; pinId++)+    {+        /* Create the pin with this Id */+        PaWinWdmPin* newPin;+        newPin = PinNew(filter, pinId, &result);+        if( result == paInsufficientMemory )+            goto error;+        if( newPin != NULL )+        {+            filter->pins[pinId] = newPin;+            ++filter->validPinCount;+        }+    }++    if (filter->validPinCount == 0)+    {+        result = paDeviceUnavailable;+        goto error;+    }++    return paNoError;++error:++    if (filter->pins)+    {+        for (pinId = 0; pinId < filter->pinCount; ++pinId)+        {+            if (filter->pins[pinId])+            {+                PaUtil_FreeMemory(filter->pins[pinId]);+                filter->pins[pinId] = 0;+            }+        }+        PaUtil_FreeMemory( filter->pins );+        filter->pins = 0;+    }++    return result;+}+++/**+* Free a previously created filter+*/+static void FilterFree(PaWinWdmFilter* filter)+{+    int pinId;+    PA_LOGL_;+    if( filter )+    {+        if (--filter->filterRefCount > 0)+        {+            /* Ok, a stream has a ref count to this filter */+            return;+        }++        if (filter->topologyFilter)+        {+            FilterFree(filter->topologyFilter);+            filter->topologyFilter = 0;+        }+        if ( filter->pins )+        {+            for( pinId = 0; pinId < filter->pinCount; pinId++ )+                PinFree(filter->pins[pinId]);+            PaUtil_FreeMemory( filter->pins );+            filter->pins = 0;+        }+        if( filter->connections )+        {+            PaUtil_FreeMemory(filter->connections);+            filter->connections = 0;+        }+        if( filter->nodes )+        {+            PaUtil_FreeMemory(filter->nodes);+            filter->nodes = 0;+        }+        if( filter->handle )+            CloseHandle( filter->handle );+        PaUtil_FreeMemory( filter );+    }+    PA_LOGE_;+}++/**+* Reopen the filter handle if necessary so it can be used+**/+static PaError FilterUse(PaWinWdmFilter* filter)+{+    assert( filter );++    PA_LOGE_;+    if( filter->handle == NULL )+    {+        /* Open the filter */+        filter->handle = CreateFileW(+            filter->devInfo.filterPath,+            GENERIC_READ | GENERIC_WRITE,+            0,+            NULL,+            OPEN_EXISTING,+            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,+            NULL);++        if( filter->handle == NULL )+        {+            return paDeviceUnavailable;+        }+    }+    filter->usageCount++;+    PA_LOGL_;+    return paNoError;+}++/**+* Release the filter handle if nobody is using it+**/+static void FilterRelease(PaWinWdmFilter* filter)+{+    assert( filter );+    assert( filter->usageCount > 0 );++    PA_LOGE_;+    /* Check first topology filter, if used */+    if (filter->topologyFilter != NULL && filter->topologyFilter->handle != NULL)+    {+        FilterRelease(filter->topologyFilter);+    }++    filter->usageCount--;+    if( filter->usageCount == 0 )+    {+        if( filter->handle != NULL )+        {+            CloseHandle( filter->handle );+            filter->handle = NULL;+        }+    }+    PA_LOGL_;+}++/**+* Create a render or playback pin using the supplied format+**/+static PaWinWdmPin* FilterCreatePin(PaWinWdmFilter* filter,+                                    int pinId,+                                    const WAVEFORMATEX* wfex,+                                    PaError* error)+{+    PaError result = paNoError;+    PaWinWdmPin* pin = NULL;+    assert( filter );+    assert( pinId < filter->pinCount );+    pin = filter->pins[pinId];+    assert( pin );+    result = PinSetFormat(pin,wfex);+    if( result == paNoError )+    {+        result = PinInstantiate(pin);+    }+    *error = result;+    return result == paNoError ? pin : 0;+}++static const wchar_t kUsbPrefix[] = L"\\\\?\\USB";++static BOOL IsUSBDevice(const wchar_t* devicePath)+{+    /* Alex Lessard pointed out that different devices might present the device path with+       lower case letters. */+    return (_wcsnicmp(devicePath, kUsbPrefix, sizeof(kUsbPrefix)/sizeof(kUsbPrefix[0]) ) == 0);+}++/* This should make it more language tolerant, I hope... */+static const wchar_t kUsbNamePrefix[] = L"USB Audio";++static BOOL IsNameUSBAudioDevice(const wchar_t* friendlyName)+{+    return (_wcsnicmp(friendlyName, kUsbNamePrefix, sizeof(kUsbNamePrefix)/sizeof(kUsbNamePrefix[0])) == 0);+}++typedef enum _tag_EAlias+{+    Alias_kRender   = (1<<0),+    Alias_kCapture  = (1<<1),+    Alias_kRealtime = (1<<2),+} EAlias;++/* Trim whitespace from string */+static void TrimString(wchar_t* str, size_t length)+{+    wchar_t* s = str;+    wchar_t* e = 0;++    /* Find start of string */+    while (iswspace(*s)) ++s;+    e=s+min(length,wcslen(s))-1;++    /* Find end of string */+    while(e>s && iswspace(*e)) --e;+    ++e;++    length = e - s;+    memmove(str, s, length * sizeof(wchar_t));+    str[length] = 0;+}++/**+* Build the list of available filters+* Use the SetupDi API to enumerate all devices in the KSCATEGORY_AUDIO which +* have a KSCATEGORY_RENDER or KSCATEGORY_CAPTURE alias. For each of these +* devices initialise a PaWinWdmFilter structure by calling our NewFilter() +* function. We enumerate devices twice, once to count how many there are, +* and once to initialize the PaWinWdmFilter structures.+*+* Vista and later: Also check KSCATEGORY_REALTIME for WaveRT devices.+*/+//PaError BuildFilterList( PaWinWdmHostApiRepresentation* wdmHostApi, int* noOfPaDevices )+PaWinWdmFilter** BuildFilterList( int* pFilterCount, int* pNoOfPaDevices, PaError* pResult )+{+    PaWinWdmFilter** ppFilters = NULL;+    HDEVINFO handle = NULL;+    int device;+    int invalidDevices;+    int slot;+    SP_DEVICE_INTERFACE_DATA interfaceData;+    SP_DEVICE_INTERFACE_DATA aliasData;+    SP_DEVINFO_DATA devInfoData;+    int noError;+    const int sizeInterface = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR));+    unsigned char interfaceDetailsArray[sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR))];+    SP_DEVICE_INTERFACE_DETAIL_DATA_W* devInterfaceDetails = (SP_DEVICE_INTERFACE_DETAIL_DATA_W*)interfaceDetailsArray;+    const GUID* category = (const GUID*)&KSCATEGORY_AUDIO;+    const GUID* alias_render = (const GUID*)&KSCATEGORY_RENDER;+    const GUID* alias_capture = (const GUID*)&KSCATEGORY_CAPTURE;+    const GUID* category_realtime = (const GUID*)&KSCATEGORY_REALTIME;+    DWORD aliasFlags;+    PaWDMKSType streamingType;+    int filterCount = 0;+    int noOfPaDevices = 0;++    PA_LOGE_;++    assert(pFilterCount != NULL);+    assert(pNoOfPaDevices != NULL);+    assert(pResult != NULL);++    devInterfaceDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);+    *pFilterCount = 0;+    *pNoOfPaDevices = 0;++    /* Open a handle to search for devices (filters) */+    handle = SetupDiGetClassDevs(category,NULL,NULL,DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);+    if( handle == INVALID_HANDLE_VALUE )+    {+        *pResult = paUnanticipatedHostError;+        return NULL;+    }+    PA_DEBUG(("Setup called\n"));++    /* First let's count the number of devices so we can allocate a list */+    invalidDevices = 0;+    for( device = 0;;device++ )+    {+        interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);+        interfaceData.Reserved = 0;+        aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);+        aliasData.Reserved = 0;+        noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);+        PA_DEBUG(("Enum called\n"));+        if( !noError )+            break; /* No more devices */++        /* Check this one has the render or capture alias */+        aliasFlags = 0;+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);+        PA_DEBUG(("noError = %d\n",noError));+        if(noError)+        {+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))+            {+                PA_DEBUG(("Device %d has render alias\n",device));+                aliasFlags |= Alias_kRender; /* Has render alias */+            }+            else+            {+                PA_DEBUG(("Device %d has no render alias\n",device));+            }+        }+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);+        if(noError)+        {+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))+            {+                PA_DEBUG(("Device %d has capture alias\n",device));+                aliasFlags |= Alias_kCapture; /* Has capture alias */+            }+            else+            {+                PA_DEBUG(("Device %d has no capture alias\n",device));+            }+        }+        if(!aliasFlags)+            invalidDevices++; /* This was not a valid capture or render audio device */+    }+    /* Remember how many there are */+    filterCount = device-invalidDevices;++    PA_DEBUG(("Interfaces found: %d\n",device-invalidDevices));++    /* Now allocate the list of pointers to devices */+    ppFilters  = (PaWinWdmFilter**)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter*) * filterCount);+    if( ppFilters == 0 )+    {+        if(handle != NULL)+            SetupDiDestroyDeviceInfoList(handle);+        *pResult = paInsufficientMemory;+        return NULL;+    }++    /* Now create filter objects for each interface found */+    slot = 0;+    for( device = 0;;device++ )+    {+        interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);+        interfaceData.Reserved = 0;+        aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);+        aliasData.Reserved = 0;+        devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);+        devInfoData.Reserved = 0;+        streamingType = Type_kWaveCyclic;++        noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);+        if( !noError )+            break; /* No more devices */++        /* Check this one has the render or capture alias */+        aliasFlags = 0;+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);+        if(noError)+        {+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))+            {+                PA_DEBUG(("Device %d has render alias\n",device));+                aliasFlags |= Alias_kRender; /* Has render alias */+            }+        }+        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);+        if(noError)+        {+            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))+            {+                PA_DEBUG(("Device %d has capture alias\n",device));+                aliasFlags |= Alias_kCapture; /* Has capture alias */+            }+        }+        if(!aliasFlags)+        {+            continue; /* This was not a valid capture or render audio device */+        }+        else+        {+            /* Check if filter is WaveRT, if not it is a WaveCyclic */+            noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,category_realtime,&aliasData);+            if (noError)+            {+                PA_DEBUG(("Device %d has realtime alias\n",device));+                aliasFlags |= Alias_kRealtime;+                streamingType = Type_kWaveRT;+            }+        }++        noError = SetupDiGetDeviceInterfaceDetailW(handle,&interfaceData,devInterfaceDetails,sizeInterface,NULL,&devInfoData);+        if( noError )+        {+            DWORD type;+            WCHAR friendlyName[MAX_PATH] = {0};+            DWORD sizeFriendlyName;+            PaWinWdmFilter* newFilter = 0;++            PaError result = paNoError;+            /* Try to get the "friendly name" for this interface */+            sizeFriendlyName = sizeof(friendlyName);++            if (IsEarlierThanVista() && IsUSBDevice(devInterfaceDetails->DevicePath))+            {+                /* XP and USB audio device needs to look elsewhere, otherwise it'll only be a "USB Audio Device". Not+                very literate. */+                if (!SetupDiGetDeviceRegistryPropertyW(handle,+                    &devInfoData,+                    SPDRP_LOCATION_INFORMATION, +                    &type,+                    (BYTE*)friendlyName,+                    sizeof(friendlyName),+                    NULL))+                {+                    friendlyName[0] = 0;+                }+            }++            if (friendlyName[0] == 0 || IsNameUSBAudioDevice(friendlyName))+            {+                /* Fix contributed by Ben Allison+                * Removed KEY_SET_VALUE from flags on following call+                * as its causes failure when running without admin rights+                * and it was not required */+                HKEY hkey=SetupDiOpenDeviceInterfaceRegKey(handle,&interfaceData,0,KEY_QUERY_VALUE);+                if(hkey!=INVALID_HANDLE_VALUE)+                {+                    noError = RegQueryValueExW(hkey,L"FriendlyName",0,&type,(BYTE*)friendlyName,&sizeFriendlyName);+                    if( noError == ERROR_SUCCESS )+                    {+                        PA_DEBUG(("Interface %d, Name: %s\n",device,friendlyName));+                        RegCloseKey(hkey);+                    }+                    else+                    {+                        friendlyName[0] = 0;+                    }+                }+            }++            TrimString(friendlyName, sizeFriendlyName);++            newFilter = FilterNew(streamingType, +                devInfoData.DevInst,+                devInterfaceDetails->DevicePath,+                friendlyName,+                &result);++            if( result == paNoError )+            {+                int pin;+                unsigned filterIOs = 0;++                /* Increment number of "devices" */+                for (pin = 0; pin < newFilter->pinCount; ++pin)+                {+                    PaWinWdmPin* pPin = newFilter->pins[pin];+                    if (pPin == NULL)+                        continue;++                    filterIOs += max(1, pPin->inputCount);+                }++                noOfPaDevices += filterIOs;++                PA_DEBUG(("Filter (%s) created with %d valid pins (total I/Os: %u)\n", ((newFilter->devInfo.streamingType==Type_kWaveRT)?"WaveRT":"WaveCyclic"), newFilter->validPinCount, filterIOs));++                assert(slot < filterCount);++                ppFilters[slot] = newFilter;++                slot++;+            }+            else+            {+                PA_DEBUG(("Filter NOT created\n"));+                /* As there are now less filters than we initially thought+                * we must reduce the count by one */+                filterCount--;+            }+        }+    }++    /* Clean up */+    if(handle != NULL)+        SetupDiDestroyDeviceInfoList(handle);++    *pFilterCount = filterCount;+    *pNoOfPaDevices = noOfPaDevices;++    return ppFilters;+}++typedef struct PaNameHashIndex+{+    unsigned index;+    unsigned count;+    ULONG    hash;+    struct PaNameHashIndex *next;+} PaNameHashIndex;++typedef struct PaNameHashObject+{+    PaNameHashIndex* list;+    PaUtilAllocationGroup* allocGroup;+} PaNameHashObject;++static ULONG GetNameHash(const wchar_t* str, const BOOL input)+{+    /* This is to make sure that a name that exists as both input & output won't get the same hash value */+    const ULONG fnv_prime = (input ? 0x811C9DD7 : 0x811FEB0B);+    ULONG hash = 0;+    for(; *str != 0; str++)+    {+        hash *= fnv_prime;+        hash ^= (*str);+    }+    assert(hash != 0);+    return hash;+}++static PaError CreateHashEntry(PaNameHashObject* obj, const wchar_t* name, const BOOL input)+{+    ULONG hash = GetNameHash(name, input); +    PaNameHashIndex * pLast = NULL;+    PaNameHashIndex * p = obj->list;+    while (p != 0)+    {+        if (p->hash == hash)+        {+            break;+        }+        pLast = p;+        p = p->next;+    }+    if (p == NULL)+    {+        p = (PaNameHashIndex*)PaUtil_GroupAllocateMemory(obj->allocGroup, sizeof(PaNameHashIndex));+        if (p == NULL)+        {+            return paInsufficientMemory;+        }+        p->hash = hash;+        p->count = 1;+        if (pLast != 0)+        {+            assert(pLast->next == 0);+            pLast->next = p;+        }+        if (obj->list == 0)+        {+            obj->list = p;+        }+    }+    else+    {+        ++p->count;+    }+    return paNoError;+}++static PaError InitNameHashObject(PaNameHashObject* obj, PaWinWdmFilter* pFilter)+{+    int i;++    obj->allocGroup = PaUtil_CreateAllocationGroup();+    if (obj->allocGroup == NULL)+    {+        return paInsufficientMemory;+    }++    for (i = 0; i < pFilter->pinCount; ++i)+    {+        unsigned m;+        PaWinWdmPin* pin = pFilter->pins[i];++        if (pin == NULL)+            continue;++        for (m = 0; m < max(1, pin->inputCount); ++m)+        {+            const BOOL isInput = (pin->dataFlow == KSPIN_DATAFLOW_OUT);+            const wchar_t* name = (pin->inputs == NULL) ? pin->friendlyName : pin->inputs[m]->friendlyName;++            PaError result = CreateHashEntry(obj, name, isInput);++            if (result != paNoError)+            {+                return result;+            }+        }+    }+    return paNoError;+}++static void DeinitNameHashObject(PaNameHashObject* obj)+{+    assert(obj != 0);+    PaUtil_FreeAllAllocations(obj->allocGroup);+    PaUtil_DestroyAllocationGroup(obj->allocGroup);+    memset(obj, 0, sizeof(PaNameHashObject));+}++static unsigned GetNameIndex(PaNameHashObject* obj, const wchar_t* name, const BOOL input)+{+    ULONG hash = GetNameHash(name, input); +    PaNameHashIndex* p = obj->list;+    while (p != NULL)+    {+        if (p->hash == hash)+        {+            if (p->count > 1)+            {+                return (++p->index);+            }+            else+            {+                return 0;+            }+        }++        p = p->next;+    }+    // Should never get here!!+    assert(FALSE);+    return 0;+}++static PaError ScanDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex hostApiIndex, void **scanResults, int *newDeviceCount )+{+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;+    PaError result = paNoError;+    PaWinWdmFilter** ppFilters = 0;+    PaWinWDMScanDeviceInfosResults *outArgument = 0;+    int filterCount = 0;+    int totalDeviceCount = 0;+    int idxDevice = 0;++    ppFilters = BuildFilterList( &filterCount, &totalDeviceCount, &result );+    if( result != paNoError )+    {+        goto error;+    }++    if( totalDeviceCount > 0 )+    {+        PaWinWdmDeviceInfo *deviceInfoArray = 0;+        int idxFilter;+        int i;++        /* Allocate the out param for all the info we need */+        outArgument = (PaWinWDMScanDeviceInfosResults *) PaUtil_GroupAllocateMemory(+            wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults) );+        if( !outArgument )+        {+            result = paInsufficientMemory;+            goto error;+        }++        outArgument->defaultInputDevice  = paNoDevice;+        outArgument->defaultOutputDevice = paNoDevice;++        outArgument->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(+            wdmHostApi->allocations, sizeof(PaDeviceInfo*) * totalDeviceCount );+        if( !outArgument->deviceInfos )+        {+            result = paInsufficientMemory;+            goto error;+        }++        /* allocate all device info structs in a contiguous block */+        deviceInfoArray = (PaWinWdmDeviceInfo*)PaUtil_GroupAllocateMemory(+            wdmHostApi->allocations, sizeof(PaWinWdmDeviceInfo) * totalDeviceCount );+        if( !deviceInfoArray )+        {+            result = paInsufficientMemory;+            goto error;+        }++        /* Make sure all items in array */+        for( i = 0 ; i < totalDeviceCount; ++i )+        {+            PaDeviceInfo *deviceInfo  = &deviceInfoArray[i].inheritedDeviceInfo;+            deviceInfo->structVersion = 2;+            deviceInfo->hostApi       = hostApiIndex;+            deviceInfo->name          = 0;+            outArgument->deviceInfos[ i ] = deviceInfo;+        }++        idxDevice = 0;+        for (idxFilter = 0; idxFilter < filterCount; ++idxFilter)+        {+            PaNameHashObject nameHash = {0};+            PaWinWdmFilter* pFilter = ppFilters[idxFilter];+            if( pFilter == NULL )+                continue;++            if (InitNameHashObject(&nameHash, pFilter) != paNoError)+            {+                DeinitNameHashObject(&nameHash);+                continue;+            }++            for (i = 0; i < pFilter->pinCount; ++i)+            {+                unsigned m;+                ULONG nameIndex = 0;+                ULONG nameIndexHash = 0;+                PaWinWdmPin* pin = pFilter->pins[i];++                if (pin == NULL)+                    continue;++                for (m = 0; m < max(1, pin->inputCount); ++m)+                {+                    PaWinWdmDeviceInfo *wdmDeviceInfo = (PaWinWdmDeviceInfo *)outArgument->deviceInfos[idxDevice];+                    PaDeviceInfo *deviceInfo = &wdmDeviceInfo->inheritedDeviceInfo;+                    wchar_t localCompositeName[MAX_PATH];+                    unsigned nameIndex = 0;+                    const BOOL isInput = (pin->dataFlow == KSPIN_DATAFLOW_OUT);++                    wdmDeviceInfo->filter = pFilter;++                    deviceInfo->structVersion = 2;+                    deviceInfo->hostApi = hostApiIndex;+                    deviceInfo->name = wdmDeviceInfo->compositeName;+                    /* deviceInfo->hostApiSpecificDeviceInfo = &pFilter->devInfo; */++                    wdmDeviceInfo->pin = pin->pinId;++                    /* Get the name of the "device" */+                    if (pin->inputs == NULL)+                    {+                        wcsncpy(localCompositeName, pin->friendlyName, MAX_PATH);+                        wdmDeviceInfo->muxPosition = -1;+                        wdmDeviceInfo->endpointPinId = pin->endpointPinId;+                    }+                    else+                    {+                        PaWinWdmMuxedInput* input = pin->inputs[m];+                        wcsncpy(localCompositeName, input->friendlyName, MAX_PATH);+                        wdmDeviceInfo->muxPosition = (int)m;+                        wdmDeviceInfo->endpointPinId = input->endpointPinId;+                    }++                    {+                        /* Get base length */+                        size_t n = wcslen(localCompositeName);++                        /* Check if there are more entries with same name (which might very well be the case), if there+                        are, the name will be postfixed with an index. */+                        nameIndex = GetNameIndex(&nameHash, localCompositeName, isInput);+                        if (nameIndex > 0)+                        {+                            /* This name has multiple instances, so we post fix with a number */+                            n += _snwprintf(localCompositeName + n, MAX_PATH - n, L" %u", nameIndex);+                        }+                        /* Postfix with filter name */+                        _snwprintf(localCompositeName + n, MAX_PATH - n, L" (%s)", pFilter->friendlyName);+                    }++                    /* Convert wide char string to utf-8 */+                    WideCharToMultiByte(CP_UTF8, 0, localCompositeName, -1, wdmDeviceInfo->compositeName, MAX_PATH, NULL, NULL);++                    /* NB! WDM/KS has no concept of a full-duplex device, each pin is either an input or and output */+                    if (isInput)+                    {+                        /* INPUT ! */+                        deviceInfo->maxInputChannels  = pin->maxChannels;+                        deviceInfo->maxOutputChannels = 0;++                        if (outArgument->defaultInputDevice == paNoDevice)+                        {+                            outArgument->defaultInputDevice = idxDevice;+                        }+                    }+                    else+                    {+                        /* OUTPUT ! */+                        deviceInfo->maxInputChannels  = 0;+                        deviceInfo->maxOutputChannels = pin->maxChannels;++                        if (outArgument->defaultOutputDevice == paNoDevice)+                        {+                            outArgument->defaultOutputDevice = idxDevice;+                        }+                    }++                    /* These low values are not very useful because+                    * a) The lowest latency we end up with can depend on many factors such+                    *    as the device buffer sizes/granularities, sample rate, channels and format+                    * b) We cannot know the device buffer sizes until we try to open/use it at+                    *    a particular setting+                    * So: we give 512x48000Hz frames as the default low input latency+                    **/+                    switch (pFilter->devInfo.streamingType)+                    {+                    case Type_kWaveCyclic:+                        if (IsEarlierThanVista())+                        {+                            /* XP doesn't tolerate low latency, unless the Process Priority Class is set to REALTIME_PRIORITY_CLASS +                            through SetPriorityClass, then 10 ms is quite feasible. However, one should then bear in mind that ALL of+                            the process is running in REALTIME_PRIORITY_CLASS, which might not be appropriate for an application with+                            a GUI . In this case it is advisable to separate the audio engine in another process and use IPC to communicate+                            with it. */+                            deviceInfo->defaultLowInputLatency = 0.02;+                            deviceInfo->defaultLowOutputLatency = 0.02;+                        }+                        else+                        {+                            /* This is a conservative estimate. Most WaveCyclic drivers will limit the available latency, but f.i. my Edirol+                            PCR-A30 can reach 3 ms latency easily... */+                            deviceInfo->defaultLowInputLatency = 0.01;+                            deviceInfo->defaultLowOutputLatency = 0.01;+                        }+                        deviceInfo->defaultHighInputLatency = (4096.0/48000.0);+                        deviceInfo->defaultHighOutputLatency = (4096.0/48000.0);+                        deviceInfo->defaultSampleRate = (double)(pin->defaultSampleRate);+                        break;+                    case Type_kWaveRT:+                        /* This is also a conservative estimate, based on WaveRT polled mode. In polled mode, the latency will be dictated+                        by the buffer size given by the driver. */+                        deviceInfo->defaultLowInputLatency = 0.01;+                        deviceInfo->defaultLowOutputLatency = 0.01;+                        deviceInfo->defaultHighInputLatency = 0.04;+                        deviceInfo->defaultHighOutputLatency = 0.04;+                        deviceInfo->defaultSampleRate = (double)(pin->defaultSampleRate);+                        break;+                    default:+                        assert(0);+                        break;+                    }++                    /* Add reference to filter */+                    FilterAddRef(wdmDeviceInfo->filter);++                    assert(idxDevice < totalDeviceCount);+                    ++idxDevice;+                }+            }++            /* If no one has add ref'd the filter, drop it */+            if (pFilter->filterRefCount == 0)+            {+                FilterFree(pFilter);+            }++            /* Deinitialize name hash object */+            DeinitNameHashObject(&nameHash);+        }+    }++    *scanResults = outArgument;+    *newDeviceCount = idxDevice;+    return result;++error:+    result = DisposeDeviceInfos(hostApi, outArgument, totalDeviceCount);++    return result;+}++static PaError CommitDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void *scanResults, int deviceCount )+{+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;++    hostApi->info.deviceCount = 0;+    hostApi->info.defaultInputDevice = paNoDevice;+    hostApi->info.defaultOutputDevice = paNoDevice;++    /* Free any old memory which might be in the device info */+    if( hostApi->deviceInfos )+    {+        PaWinWDMScanDeviceInfosResults* localScanResults = (PaWinWDMScanDeviceInfosResults*)PaUtil_GroupAllocateMemory(+            wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults));+        localScanResults->deviceInfos = hostApi->deviceInfos;++        DisposeDeviceInfos(hostApi, &localScanResults, hostApi->info.deviceCount);++        hostApi->deviceInfos = NULL;+    }++    if( scanResults != NULL )+    {+        PaWinWDMScanDeviceInfosResults *scanDeviceInfosResults = ( PaWinWDMScanDeviceInfosResults * ) scanResults;++        if( deviceCount > 0 )+        {+            /* use the array allocated in ScanDeviceInfos() as our deviceInfos */+            hostApi->deviceInfos = scanDeviceInfosResults->deviceInfos;++            hostApi->info.defaultInputDevice = scanDeviceInfosResults->defaultInputDevice;+            hostApi->info.defaultOutputDevice = scanDeviceInfosResults->defaultOutputDevice;++            hostApi->info.deviceCount = deviceCount;+        }++        PaUtil_GroupFreeMemory( wdmHostApi->allocations, scanDeviceInfosResults );+    }++    return paNoError;++}++static PaError DisposeDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, void *scanResults, int deviceCount )+{+    PaWinWdmHostApiRepresentation *winDsHostApi = (PaWinWdmHostApiRepresentation*)hostApi;++    if( scanResults != NULL )+    {+        PaWinWDMScanDeviceInfosResults *scanDeviceInfosResults = ( PaWinWDMScanDeviceInfosResults * ) scanResults;++        if( scanDeviceInfosResults->deviceInfos )+        {+            int i;+            for (i = 0; i < deviceCount; ++i)+            {+                PaWinWdmDeviceInfo* pDevice = (PaWinWdmDeviceInfo*)scanDeviceInfosResults->deviceInfos[i];+                if (pDevice->filter != 0)+                {+                    FilterFree(pDevice->filter);+                }+            }++            PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults->deviceInfos[0] ); /* all device info structs are allocated in a block so we can destroy them here */+            PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults->deviceInfos );+        }++        PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults );+    }++    return paNoError;++}++PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )+{+    PaError result = paNoError;+    int deviceCount = 0;+    void *scanResults = 0;+    PaWinWdmHostApiRepresentation *wdmHostApi = NULL;++    PA_LOGE_;++#ifdef PA_WDMKS_SET_TREF+    tRef = PaUtil_GetTime();+#endif++    /*+    Attempt to load the KSUSER.DLL without which we cannot create pins+    We will unload this on termination+    */+    if(DllKsUser == NULL)+    {+        DllKsUser = LoadLibrary(TEXT("ksuser.dll"));+        if(DllKsUser == NULL)+            goto error;+    }+    FunctionKsCreatePin = (KSCREATEPIN*)GetProcAddress(DllKsUser, "KsCreatePin");+    if(FunctionKsCreatePin == NULL)+        goto error;++    /* Attempt to load AVRT.DLL, if we can't, then we'll just use time critical prio instead... */+    if(paWinWDMKSAvRtEntryPoints.hInstance == NULL)+    {+        paWinWDMKSAvRtEntryPoints.hInstance = LoadLibrary(TEXT("avrt.dll"));+        if (paWinWDMKSAvRtEntryPoints.hInstance != NULL)+        {+            paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics =+                (HANDLE(WINAPI*)(LPCSTR,LPDWORD))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance,"AvSetMmThreadCharacteristicsA");+            paWinWDMKSAvRtEntryPoints.AvRevertMmThreadCharacteristics =+                (BOOL(WINAPI*)(HANDLE))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance, "AvRevertMmThreadCharacteristics");+            paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority =+                (BOOL(WINAPI*)(HANDLE,PA_AVRT_PRIORITY))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance, "AvSetMmThreadPriority");+        }+    }++    wdmHostApi = (PaWinWdmHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinWdmHostApiRepresentation) );+    if( !wdmHostApi )+    {+        result = paInsufficientMemory;+        goto error;+    }++    wdmHostApi->allocations = PaUtil_CreateAllocationGroup();+    if( !wdmHostApi->allocations )+    {+        result = paInsufficientMemory;+        goto error;+    }++    *hostApi = &wdmHostApi->inheritedHostApiRep;+    (*hostApi)->info.structVersion = 1;+    (*hostApi)->info.type = paWDMKS;+    (*hostApi)->info.name = "Windows WDM-KS";++    /* these are all updated by CommitDeviceInfos() */+    (*hostApi)->info.deviceCount = 0;+    (*hostApi)->info.defaultInputDevice = paNoDevice;+    (*hostApi)->info.defaultOutputDevice = paNoDevice;+    (*hostApi)->deviceInfos = 0;++    result = ScanDeviceInfos(&wdmHostApi->inheritedHostApiRep, hostApiIndex, &scanResults, &deviceCount);+    if (result != paNoError)+    {+        goto error;+    }++    CommitDeviceInfos(&wdmHostApi->inheritedHostApiRep, hostApiIndex, scanResults, deviceCount);++    (*hostApi)->Terminate = Terminate;+    (*hostApi)->OpenStream = OpenStream;+    (*hostApi)->IsFormatSupported = IsFormatSupported;+    /* In preparation for hotplug+    (*hostApi)->ScanDeviceInfos = ScanDeviceInfos;+    (*hostApi)->CommitDeviceInfos = CommitDeviceInfos;+    (*hostApi)->DisposeDeviceInfos = DisposeDeviceInfos;+    */+    PaUtil_InitializeStreamInterface( &wdmHostApi->callbackStreamInterface, CloseStream, StartStream,+        StopStream, AbortStream, IsStreamStopped, IsStreamActive,+        GetStreamTime, GetStreamCpuLoad,+        PaUtil_DummyRead, PaUtil_DummyWrite,+        PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );++    PaUtil_InitializeStreamInterface( &wdmHostApi->blockingStreamInterface, CloseStream, StartStream,+        StopStream, AbortStream, IsStreamStopped, IsStreamActive,+        GetStreamTime, PaUtil_DummyGetCpuLoad,+        ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );++    PA_LOGL_;+    return result;++error:+    Terminate( (PaUtilHostApiRepresentation*)wdmHostApi );++    PA_LOGL_;+    return result;+}+++static void Terminate( struct PaUtilHostApiRepresentation *hostApi )+{+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;+    PA_LOGE_;++    /* Do not unload the libraries */+    if( DllKsUser != NULL )+    {+        FreeLibrary( DllKsUser );+        DllKsUser = NULL;+    }++    if( paWinWDMKSAvRtEntryPoints.hInstance != NULL )+    {+        FreeLibrary( paWinWDMKSAvRtEntryPoints.hInstance );+        paWinWDMKSAvRtEntryPoints.hInstance = NULL;+    }++    if( wdmHostApi)+    {+        PaWinWDMScanDeviceInfosResults* localScanResults = (PaWinWDMScanDeviceInfosResults*)PaUtil_GroupAllocateMemory(+            wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults));+        localScanResults->deviceInfos = hostApi->deviceInfos;+        DisposeDeviceInfos(hostApi, localScanResults, hostApi->info.deviceCount);++        if( wdmHostApi->allocations )+        {+            PaUtil_FreeAllAllocations( wdmHostApi->allocations );+            PaUtil_DestroyAllocationGroup( wdmHostApi->allocations );+        }+        PaUtil_FreeMemory( wdmHostApi );+    }+    PA_LOGL_;+}++static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,+                                 const PaStreamParameters *inputParameters,+                                 const PaStreamParameters *outputParameters,+                                 double sampleRate )+{+    int inputChannelCount, outputChannelCount;+    PaSampleFormat inputSampleFormat, outputSampleFormat;+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;+    PaWinWdmFilter* pFilter;+    int result = paFormatIsSupported;+    WAVEFORMATEXTENSIBLE wfx;+    PaWinWaveFormatChannelMask channelMask;++    PA_LOGE_;++    if( inputParameters )+    {+        PaWinWdmDeviceInfo* pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];+        PaWinWdmPin* pin;+        unsigned fmt;+        unsigned long testFormat = 0;+        unsigned validBits = 0;++        inputChannelCount = inputParameters->channelCount;+        inputSampleFormat = inputParameters->sampleFormat;++        /* all standard sample formats are supported by the buffer adapter,+        this implementation doesn't support any custom sample formats */+        if( inputSampleFormat & paCustomFormat )+        {+            PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "IsFormatSupported: Custom input format not supported");+            return paSampleFormatNotSupported;+        }++        /* unless alternate device specification is supported, reject the use of+        paUseHostApiSpecificDeviceSpecification */++        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "IsFormatSupported: paUseHostApiSpecificDeviceSpecification not supported");+            return paInvalidDevice;+        }++        /* check that input device can support inputChannelCount */+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "IsFormatSupported: Invalid input channel count");+            return paInvalidChannelCount;+        }++        /* validate inputStreamInfo */+        if( inputParameters->hostApiSpecificStreamInfo )+        {+            PaWinWDM_SetLastErrorInfo(paIncompatibleHostApiSpecificStreamInfo, "Host API stream info not supported");+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */+        }++        pFilter = pDeviceInfo->filter;+        pin = pFilter->pins[pDeviceInfo->pin];++        /* Find out the testing format */+        for (fmt = paFloat32; fmt <= paUInt8; fmt <<= 1)+        {+            if ((fmt & pin->formats) != 0)+            {+                /* Found a matching format! */+                testFormat = fmt;+                break;+            }+        }+        if (testFormat == 0)+        {+            PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(capture) failed: no testformat found!");+            return paUnanticipatedHostError;+        }++        /* Due to special considerations, WaveRT devices with paInt24 should be tested with paInt32 and+        valid bits = 24 (instead of 24 bit samples) */+        if (pFilter->devInfo.streamingType == Type_kWaveRT && testFormat == paInt24)+        {+            PA_DEBUG(("IsFormatSupported (capture): WaveRT overriding testFormat paInt24 with paInt32 (24 valid bits)"));+            testFormat = paInt32;+            validBits = 24;+        }++        /* Check that the input format is supported */+        channelMask = PaWin_DefaultChannelMask(inputChannelCount);+        PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,+            inputChannelCount, +            testFormat,+            PaWin_SampleFormatToLinearWaveFormatTag(testFormat),+            sampleRate,+            channelMask );+        if (validBits != 0)+        {+            wfx.Samples.wValidBitsPerSample = validBits;+        }++        result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);+        if( result != paNoError )+        {+            /* Try a WAVE_FORMAT_PCM instead */+            PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,+                inputChannelCount, +                testFormat,+                PaWin_SampleFormatToLinearWaveFormatTag(testFormat),+                sampleRate);++            if (validBits != 0)+            {+                wfx.Samples.wValidBitsPerSample = validBits;+            }++            result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);+            if( result != paNoError )+            {+                PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(capture) failed: sr=%u,ch=%u,bits=%u", wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample);+                return result;+            }+        }+    }+    else+    {+        inputChannelCount = 0;+    }++    if( outputParameters )+    {+        PaWinWdmDeviceInfo* pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];+        PaWinWdmPin* pin;+        unsigned fmt;+        unsigned long testFormat = 0;+        unsigned validBits = 0;++        outputChannelCount = outputParameters->channelCount;+        outputSampleFormat = outputParameters->sampleFormat;++        /* all standard sample formats are supported by the buffer adapter,+        this implementation doesn't support any custom sample formats */+        if( outputSampleFormat & paCustomFormat )+        {+            PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "IsFormatSupported: Custom output format not supported");+            return paSampleFormatNotSupported;+        }++        /* unless alternate device specification is supported, reject the use of+        paUseHostApiSpecificDeviceSpecification */++        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "IsFormatSupported: paUseHostApiSpecificDeviceSpecification not supported");+            return paInvalidDevice;+        }++        /* check that output device can support outputChannelCount */+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid output channel count");+            return paInvalidChannelCount;+        }++        /* validate outputStreamInfo */+        if( outputParameters->hostApiSpecificStreamInfo )+        {+            PaWinWDM_SetLastErrorInfo(paIncompatibleHostApiSpecificStreamInfo, "Host API stream info not supported");+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */+        }++        pFilter = pDeviceInfo->filter;+        pin = pFilter->pins[pDeviceInfo->pin];++        /* Find out the testing format */+        for (fmt = paFloat32; fmt <= paUInt8; fmt <<= 1)+        {+            if ((fmt & pin->formats) != 0)+            {+                /* Found a matching format! */+                testFormat = fmt;+                break;+            }+        }+        if (testFormat == 0)+        {+            PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(render) failed: no testformat found!");+            return paUnanticipatedHostError;+        }++        /* Due to special considerations, WaveRT devices with paInt24 should be tested with paInt32 and+        valid bits = 24 (instead of 24 bit samples) */+        if (pFilter->devInfo.streamingType == Type_kWaveRT && testFormat == paInt24)+        {+            PA_DEBUG(("IsFormatSupported (render): WaveRT overriding testFormat paInt24 with paInt32 (24 valid bits)"));+            testFormat = paInt32;+            validBits = 24;+        }++        /* Check that the output format is supported */+        channelMask = PaWin_DefaultChannelMask(outputChannelCount);+        PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,+            outputChannelCount, +            testFormat,+            PaWin_SampleFormatToLinearWaveFormatTag(testFormat),+            sampleRate,+            channelMask );++        if (validBits != 0)+        {+            wfx.Samples.wValidBitsPerSample = validBits;+        }++        result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);+        if( result != paNoError )+        {+            /* Try a WAVE_FORMAT_PCM instead */+            PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,+                outputChannelCount, +                testFormat,+                PaWin_SampleFormatToLinearWaveFormatTag(testFormat),+                sampleRate);++            if (validBits != 0)+            {+                wfx.Samples.wValidBitsPerSample = validBits;+            }++            result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);+            if( result != paNoError )+            {+                PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(render) failed: %u,%u,%u", wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample);+                return result;+            }+        }++    }+    else+    {+        outputChannelCount = 0;+    }++    /*+    IMPLEMENT ME:++    - if a full duplex stream is requested, check that the combination+    of input and output parameters is supported if necessary++    - check that the device supports sampleRate++    Because the buffer adapter handles conversion between all standard+    sample formats, the following checks are only required if paCustomFormat+    is implemented, or under some other unusual conditions.++    - check that input device can support inputSampleFormat, or that+    we have the capability to convert from inputSampleFormat to+    a native format++    - check that output device can support outputSampleFormat, or that+    we have the capability to convert from outputSampleFormat to+    a native format+    */+    if((inputChannelCount == 0)&&(outputChannelCount == 0))+    {+        PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "No input or output channels defined");+        result = paSampleFormatNotSupported; /* Not right error */+    }++    PA_LOGL_;+    return result;+}++static void ResetStreamEvents(PaWinWdmStream* stream) +{+    unsigned i;+    ResetEvent(stream->eventAbort);+    ResetEvent(stream->eventStreamStart[StreamStart_kOk]);+    ResetEvent(stream->eventStreamStart[StreamStart_kFailed]);++    for (i=0; i<stream->capture.noOfPackets; ++i)+    {+        if (stream->capture.events && stream->capture.events[i])+        {+            ResetEvent(stream->capture.events[i]);+        }+    }++    for (i=0; i<stream->render.noOfPackets; ++i)+    {+        if (stream->render.events && stream->render.events[i])+        {+            ResetEvent(stream->render.events[i]);+        }+    }+}++static void CloseStreamEvents(PaWinWdmStream* stream) +{+    unsigned i;+    PaWinWdmIOInfo* ios[2] = { &stream->capture, &stream->render };++    if (stream->eventAbort)+    {+        CloseHandle(stream->eventAbort);+        stream->eventAbort = 0;+    }+    if (stream->eventStreamStart[StreamStart_kOk])+    {+        CloseHandle(stream->eventStreamStart[StreamStart_kOk]);+    }+    if (stream->eventStreamStart[StreamStart_kFailed])+    {+        CloseHandle(stream->eventStreamStart[StreamStart_kFailed]);+    }++    for (i = 0; i < 2; ++i)+    {+        unsigned j;+        /* Unregister notification handles for WaveRT */+        if (ios[i]->pPin && ios[i]->pPin->parentFilter->devInfo.streamingType == Type_kWaveRT &&+            ios[i]->pPin->pinKsSubType == SubType_kNotification &&+            ios[i]->events != 0)+        {+            PinUnregisterNotificationHandle(ios[i]->pPin, ios[i]->events[0]);+        }++        for (j=0; j < ios[i]->noOfPackets; ++j)+        {+            if (ios[i]->events && ios[i]->events[j])+            {+                CloseHandle(ios[i]->events[j]);+                ios[i]->events[j] = 0;+            }+        }+    }+}++static unsigned NextPowerOf2(unsigned val)+{+    val--;+    val = (val >> 1) | val;+    val = (val >> 2) | val;+    val = (val >> 4) | val;+    val = (val >> 8) | val;+    val = (val >> 16) | val;+    return ++val;+}++static PaError ValidateSpecificStreamParameters(+    const PaStreamParameters *streamParameters,+    const PaWinWDMKSInfo *streamInfo)+{+    if( streamInfo )+    {+        if( streamInfo->size != sizeof( PaWinWDMKSInfo )+            || streamInfo->version != 1 )+        {+            PA_DEBUG(("Stream parameters: size or version not correct"));+            return paIncompatibleHostApiSpecificStreamInfo;+        }++        if (streamInfo->noOfPackets != 0 &&+            (streamInfo->noOfPackets < 2 || streamInfo->noOfPackets > 8))+        {+            PA_DEBUG(("Stream parameters: noOfPackets %u out of range [2,8]", streamInfo->noOfPackets));+            return paIncompatibleHostApiSpecificStreamInfo;+        }++    }++    return paNoError;+}++++/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */++static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,+                          PaStream** s,+                          const PaStreamParameters *inputParameters,+                          const PaStreamParameters *outputParameters,+                          double sampleRate,+                          unsigned long framesPerUserBuffer,+                          PaStreamFlags streamFlags,+                          PaStreamCallback *streamCallback,+                          void *userData )+{+    PaError result = paNoError;+    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;+    PaWinWdmStream *stream = 0;+    /* unsigned long framesPerHostBuffer; these may not be equivalent for all implementations */+    PaSampleFormat inputSampleFormat, outputSampleFormat;+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;+    int userInputChannels,userOutputChannels;+    WAVEFORMATEXTENSIBLE wfx;++    PA_LOGE_;+    PA_DEBUG(("OpenStream:sampleRate = %f\n",sampleRate));+    PA_DEBUG(("OpenStream:framesPerBuffer = %lu\n",framesPerUserBuffer));++    if( inputParameters )+    {+        userInputChannels = inputParameters->channelCount;+        inputSampleFormat = inputParameters->sampleFormat;++        /* unless alternate device specification is supported, reject the use of+        paUseHostApiSpecificDeviceSpecification */++        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "paUseHostApiSpecificDeviceSpecification(in) not supported");+            return paInvalidDevice;+        }++        /* check that input device can support stream->userInputChannels */+        if( userInputChannels > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid input channel count");+            return paInvalidChannelCount;+        }++        /* validate inputStreamInfo */+        result = ValidateSpecificStreamParameters(inputParameters, inputParameters->hostApiSpecificStreamInfo);+        if(result != paNoError)+        {+            PaWinWDM_SetLastErrorInfo(result, "Host API stream info not supported (in)");+            return result; /* this implementation doesn't use custom stream info */+        }+    }+    else+    {+        userInputChannels = 0;+        inputSampleFormat = hostInputSampleFormat = paInt16; /* Supress 'uninitialised var' warnings. */+    }++    if( outputParameters )+    {+        userOutputChannels = outputParameters->channelCount;+        outputSampleFormat = outputParameters->sampleFormat;++        /* unless alternate device specification is supported, reject the use of+        paUseHostApiSpecificDeviceSpecification */++        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidDevice, "paUseHostApiSpecificDeviceSpecification(out) not supported");+            return paInvalidDevice;+        }++        /* check that output device can support stream->userInputChannels */+        if( userOutputChannels > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )+        {+            PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid output channel count");+            return paInvalidChannelCount;+        }++        /* validate outputStreamInfo */+        result = ValidateSpecificStreamParameters( outputParameters, outputParameters->hostApiSpecificStreamInfo );+        if (result != paNoError)+        {+            PaWinWDM_SetLastErrorInfo(result, "Host API stream info not supported (out)");+            return result; /* this implementation doesn't use custom stream info */+        }+    }+    else+    {+        userOutputChannels = 0;+        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Supress 'uninitialized var' warnings. */+    }++    /* validate platform specific flags */+    if( (streamFlags & paPlatformSpecificFlags) != 0 )+    {+        PaWinWDM_SetLastErrorInfo(paInvalidFlag, "Invalid flag supplied");+        return paInvalidFlag; /* unexpected platform specific flag */+    }++    stream = (PaWinWdmStream*)PaUtil_AllocateMemory( sizeof(PaWinWdmStream) );+    if( !stream )+    {+        result = paInsufficientMemory;+        goto error;+    }++    /* Create allocation group */+    stream->allocGroup = PaUtil_CreateAllocationGroup();+    if( !stream->allocGroup )+    {+        result = paInsufficientMemory;+        goto error;+    }++    /* Zero the stream object */+    /* memset((void*)stream,0,sizeof(PaWinWdmStream)); */++    if( streamCallback )+    {+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,+            &wdmHostApi->callbackStreamInterface, streamCallback, userData );+    }+    else+    {+        /* PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,+        &wdmHostApi->blockingStreamInterface, streamCallback, userData ); */++        /* We don't support the blocking API yet */+        PA_DEBUG(("Blocking API not supported yet!\n"));+        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Blocking API not supported yet");+        result = paUnanticipatedHostError;+        goto error;+    }++    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );++    /* Instantiate the input pin if necessary */+    if(userInputChannels > 0)+    {+        PaWinWdmFilter* pFilter;+        PaWinWdmDeviceInfo* pDeviceInfo;+        PaWinWdmPin* pPin;+        unsigned validBitsPerSample = 0;+        PaWinWaveFormatChannelMask channelMask = PaWin_DefaultChannelMask( userInputChannels );++        result = paSampleFormatNotSupported;+        pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];+        pFilter = pDeviceInfo->filter;+        pPin = pFilter->pins[pDeviceInfo->pin];++        stream->userInputChannels = userInputChannels;++        hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat( pPin->formats, inputSampleFormat );+        if (hostInputSampleFormat == paSampleFormatNotSupported)+        {+            result = paUnanticipatedHostError;+            PaWinWDM_SetLastErrorInfo(result, "PU_SCAF(%X,%X) failed (input)", pPin->formats, inputSampleFormat);+            goto error;+        }+        else if (pFilter->devInfo.streamingType == Type_kWaveRT && hostInputSampleFormat == paInt24)+        {+            /* For WaveRT, we choose 32 bit format instead of paInt24, since we MIGHT need to align buffer on a+            128 byte boundary (see PinGetBuffer) */+            hostInputSampleFormat = paInt32;+            /* But we'll tell the driver that it's 24 bit in 32 bit container */+            validBitsPerSample = 24;+        }++        while (hostInputSampleFormat <= paUInt8)+        {+            unsigned channelsToProbe = stream->userInputChannels;+            /* Some or all KS devices can only handle the exact number of channels+            * they specify. But PortAudio clients expect to be able to+            * at least specify mono I/O on a multi-channel device+            * If this is the case, then we will do the channel mapping internally+            * The following loop tests this case+            **/+            while (1)+            {+                PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,+                    channelsToProbe, +                    hostInputSampleFormat,+                    PaWin_SampleFormatToLinearWaveFormatTag(hostInputSampleFormat),+                    sampleRate,+                    channelMask );+                stream->capture.bytesPerFrame = wfx.Format.nBlockAlign;+                if (validBitsPerSample != 0)+                {+                    wfx.Samples.wValidBitsPerSample = validBitsPerSample;+                }+                stream->capture.pPin = FilterCreatePin(pFilter, pPin->pinId, (WAVEFORMATEX*)&wfx, &result);+                stream->deviceInputChannels = channelsToProbe;++                if( result != paNoError && result != paDeviceUnavailable )+                {+                    /* Try a WAVE_FORMAT_PCM instead */+                    PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,+                        channelsToProbe, +                        hostInputSampleFormat,+                        PaWin_SampleFormatToLinearWaveFormatTag(hostInputSampleFormat),+                        sampleRate);+                    if (validBitsPerSample != 0)+                    {+                        wfx.Samples.wValidBitsPerSample = validBitsPerSample;+                    }+                    stream->capture.pPin = FilterCreatePin(pFilter, pPin->pinId, (const WAVEFORMATEX*)&wfx, &result);+                }++                if (result == paDeviceUnavailable) goto occupied;++                if (result == paNoError)+                {+                    /* We're done */+                    break;+                }++                if (channelsToProbe < (unsigned)pPin->maxChannels)+                {+                    /* Go to next multiple of 2 */+                    channelsToProbe = min((((channelsToProbe>>1)+1)<<1), (unsigned)pPin->maxChannels);+                    continue;+                }++                break;+            }++            if (result == paNoError)+            {+                /* We're done */+                break;+            }++            /* Go to next format in line with lower resolution */+            hostInputSampleFormat <<= 1;+        }++        if(stream->capture.pPin == NULL)+        {+            PaWinWDM_SetLastErrorInfo(result, "Failed to create capture pin: sr=%u,ch=%u,bits=%u,align=%u",+                wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample, wfx.Format.nBlockAlign);+            goto error;+        }++        /* Select correct mux input on MUX node of topology filter */+        if (pDeviceInfo->muxPosition >= 0)+        {+            assert(pPin->parentFilter->topologyFilter != NULL);++            result = FilterUse(pPin->parentFilter->topologyFilter);+            if (result != paNoError)+            {+                PaWinWDM_SetLastErrorInfo(result, "Failed to open topology filter");+                goto error;+            }++            result = WdmSetMuxNodeProperty(pPin->parentFilter->topologyFilter->handle,+                pPin->inputs[pDeviceInfo->muxPosition]->muxNodeId,+                pPin->inputs[pDeviceInfo->muxPosition]->muxPinId);++            FilterRelease(pPin->parentFilter->topologyFilter);++            if(result != paNoError)+            {+                PaWinWDM_SetLastErrorInfo(result, "Failed to set topology mux node");+                goto error;+            }+        }++        stream->capture.bytesPerSample = stream->capture.bytesPerFrame / stream->deviceInputChannels;+        stream->capture.pPin->frameSize /= stream->capture.bytesPerFrame;+        PA_DEBUG(("Capture pin frames: %d\n",stream->capture.pPin->frameSize));+    }+    else+    {+        stream->capture.pPin = NULL;+        stream->capture.bytesPerFrame = 0;+    }++    /* Instantiate the output pin if necessary */+    if(userOutputChannels > 0)+    {+        PaWinWdmFilter* pFilter;+        PaWinWdmDeviceInfo* pDeviceInfo;+        PaWinWdmPin* pPin;+        unsigned validBitsPerSample = 0;+        PaWinWaveFormatChannelMask channelMask = PaWin_DefaultChannelMask( userOutputChannels );++        result = paSampleFormatNotSupported;+        pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];+        pFilter = pDeviceInfo->filter;+        pPin = pFilter->pins[pDeviceInfo->pin];++        stream->userOutputChannels = userOutputChannels;++        hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( pPin->formats, outputSampleFormat );+        if (hostOutputSampleFormat == paSampleFormatNotSupported)+        {+            result = paUnanticipatedHostError;+            PaWinWDM_SetLastErrorInfo(result, "PU_SCAF(%X,%X) failed (output)", pPin->formats, hostOutputSampleFormat);+            goto error;+        }+        else if (pFilter->devInfo.streamingType == Type_kWaveRT && hostOutputSampleFormat == paInt24)+        {+            /* For WaveRT, we choose 32 bit format instead of paInt24, since we MIGHT need to align buffer on a+            128 byte boundary (see PinGetBuffer) */+            hostOutputSampleFormat = paInt32;+            /* But we'll tell the driver that it's 24 bit in 32 bit container */+            validBitsPerSample = 24;+        }++        while (hostOutputSampleFormat <= paUInt8)+        {+            unsigned channelsToProbe = stream->userOutputChannels;+            /* Some or all KS devices can only handle the exact number of channels+            * they specify. But PortAudio clients expect to be able to+            * at least specify mono I/O on a multi-channel device+            * If this is the case, then we will do the channel mapping internally+            * The following loop tests this case+            **/+            while (1)+            {+                PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,+                    channelsToProbe, +                    hostOutputSampleFormat,+                    PaWin_SampleFormatToLinearWaveFormatTag(hostOutputSampleFormat),+                    sampleRate,+                    channelMask );+                stream->render.bytesPerFrame = wfx.Format.nBlockAlign;+                if (validBitsPerSample != 0)+                {+                    wfx.Samples.wValidBitsPerSample = validBitsPerSample;+                }+                stream->render.pPin = FilterCreatePin(pFilter, pPin->pinId, (WAVEFORMATEX*)&wfx, &result);+                stream->deviceOutputChannels = channelsToProbe;++                if( result != paNoError && result != paDeviceUnavailable )+                {+                    PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,+                        channelsToProbe, +                        hostOutputSampleFormat,+                        PaWin_SampleFormatToLinearWaveFormatTag(hostOutputSampleFormat),+                        sampleRate);+                    if (validBitsPerSample != 0)+                    {+                        wfx.Samples.wValidBitsPerSample = validBitsPerSample;+                    }+                    stream->render.pPin = FilterCreatePin(pFilter, pPin->pinId, (const WAVEFORMATEX*)&wfx, &result);+                }++                if (result == paDeviceUnavailable) goto occupied;++                if (result == paNoError)+                {+                    /* We're done */+                    break;+                }++                if (channelsToProbe < (unsigned)pPin->maxChannels)+                {+                    /* Go to next multiple of 2 */+                    channelsToProbe = min((((channelsToProbe>>1)+1)<<1), (unsigned)pPin->maxChannels);+                    continue;+                }++                break;+            };++            if (result == paNoError)+            {+                /* We're done */+                break;+            }++            /* Go to next format in line with lower resolution */+            hostOutputSampleFormat <<= 1;+        }++        if(stream->render.pPin == NULL)+        {+            PaWinWDM_SetLastErrorInfo(result, "Failed to create render pin: sr=%u,ch=%u,bits=%u,align=%u",+                wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample, wfx.Format.nBlockAlign);+            goto error;+        }++        stream->render.bytesPerSample = stream->render.bytesPerFrame / stream->deviceOutputChannels;+        stream->render.pPin->frameSize /= stream->render.bytesPerFrame;+        PA_DEBUG(("Render pin frames: %d\n",stream->render.pPin->frameSize));+    }+    else+    {+        stream->render.pPin = NULL;+        stream->render.bytesPerFrame = 0;+    }++    /* Calculate the framesPerHostXxxxBuffer size based upon the suggested latency values */+    /* Record the buffer length */+    if(inputParameters)+    {+        /* Calculate the frames from the user's value - add a bit to round up */+        stream->capture.framesPerBuffer = (unsigned long)((inputParameters->suggestedLatency*sampleRate)+0.0001);+        if(stream->capture.framesPerBuffer > (unsigned long)sampleRate)+        { /* Upper limit is 1 second */+            stream->capture.framesPerBuffer = (unsigned long)sampleRate;+        }+        else if(stream->capture.framesPerBuffer < stream->capture.pPin->frameSize)+        {+            stream->capture.framesPerBuffer = stream->capture.pPin->frameSize;+        }+        PA_DEBUG(("Input frames chosen:%ld\n",stream->capture.framesPerBuffer));++        /* Setup number of packets to use */+        stream->capture.noOfPackets = 2;++        if (inputParameters->hostApiSpecificStreamInfo)+        {+            PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)inputParameters->hostApiSpecificStreamInfo;++            if (stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic &&+                pInfo->noOfPackets != 0)+            {+                stream->capture.noOfPackets = pInfo->noOfPackets;+            }+        }+    }++    if(outputParameters)+    {+        /* Calculate the frames from the user's value - add a bit to round up */+        stream->render.framesPerBuffer = (unsigned long)((outputParameters->suggestedLatency*sampleRate)+0.0001);+        if(stream->render.framesPerBuffer > (unsigned long)sampleRate)+        { /* Upper limit is 1 second */+            stream->render.framesPerBuffer = (unsigned long)sampleRate;+        }+        else if(stream->render.framesPerBuffer < stream->render.pPin->frameSize)+        {+            stream->render.framesPerBuffer = stream->render.pPin->frameSize;+        }+        PA_DEBUG(("Output frames chosen:%ld\n",stream->render.framesPerBuffer));++        /* Setup number of packets to use */+        stream->render.noOfPackets = 2;++        if (outputParameters->hostApiSpecificStreamInfo)+        {+            PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)outputParameters->hostApiSpecificStreamInfo;++            if (stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic &&+                pInfo->noOfPackets != 0)+            {+                stream->render.noOfPackets = pInfo->noOfPackets;+            }+        }+    }++    /* Host buffer size is bound to the largest of the input and output frame sizes */+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,+        stream->userInputChannels, inputSampleFormat, hostInputSampleFormat,+        stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat,+        sampleRate, streamFlags, framesPerUserBuffer,+        max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer), +        paUtilBoundedHostBufferSize,+        streamCallback, userData );+    if( result != paNoError )+    {+        PaWinWDM_SetLastErrorInfo(result, "PaUtil_InitializeBufferProcessor failed: ich=%u, isf=%u, hisf=%u, och=%u, osf=%u, hosf=%u, sr=%lf, flags=0x%X, fpub=%u, fphb=%u",+            stream->userInputChannels, inputSampleFormat, hostInputSampleFormat,+            stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat,+            sampleRate, streamFlags, framesPerUserBuffer,+            max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer));+        goto error;+    }++    /* Allocate/get all the buffers for host I/O */+    if (stream->userInputChannels > 0)+    {+        stream->streamRepresentation.streamInfo.inputLatency = stream->capture.framesPerBuffer / sampleRate;++        switch (stream->capture.pPin->parentFilter->devInfo.streamingType)+        {+        case Type_kWaveCyclic:+            {+                unsigned size = stream->capture.noOfPackets * stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;+                /* Allocate input host buffer */+                stream->capture.hostBuffer = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, size);+                PA_DEBUG(("Input buffer allocated (size = %u)\n", size));+                if( !stream->capture.hostBuffer )+                {+                    PA_DEBUG(("Cannot allocate host input buffer!\n"));+                    PaWinWDM_SetLastErrorInfo(paInsufficientMemory, "Failed to allocate input buffer");+                    result = paInsufficientMemory;+                    goto error;+                }+                stream->capture.hostBufferSize = size;+                PA_DEBUG(("Input buffer start = %p (size=%u)\n",stream->capture.hostBuffer, stream->capture.hostBufferSize));+                stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveCyclic;+                stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveCyclic;+            }+            break;+        case Type_kWaveRT:+            {+                const DWORD dwTotalSize = 2 * stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;+                DWORD dwRequestedSize = dwTotalSize;+                BOOL bCallMemoryBarrier = FALSE;+                ULONG hwFifoLatency = 0;+                ULONG dummy;+                result = PinGetBuffer(stream->capture.pPin, (void**)&stream->capture.hostBuffer, &dwRequestedSize, &bCallMemoryBarrier);+                if (!result) +                {+                    PA_DEBUG(("Input buffer start = %p, size = %u\n", stream->capture.hostBuffer, dwRequestedSize));+                    if (dwRequestedSize != dwTotalSize)+                    {+                        PA_DEBUG(("Buffer length changed by driver from %u to %u !\n", dwTotalSize, dwRequestedSize));+                        /* Recalculate to what the driver has given us */+                        stream->capture.framesPerBuffer = dwRequestedSize / (2 * stream->capture.bytesPerFrame);+                    }+                    stream->capture.hostBufferSize = dwRequestedSize;++                    if (stream->capture.pPin->pinKsSubType == SubType_kPolled)+                    {+                        stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveRTPolled;+                        stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveRTPolled;+                    }+                    else+                    {+                        stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveRTEvent;+                        stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveRTEvent;+                    }++                    stream->capture.pPin->fnMemBarrier = bCallMemoryBarrier ? MemoryBarrierRead : MemoryBarrierDummy;+                }+                else +                {+                    PA_DEBUG(("Failed to get input buffer (WaveRT)\n"));+                    PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to get input buffer (WaveRT)");+                    result = paUnanticipatedHostError;+                    goto error;+                }++                /* Get latency */+                result = PinGetHwLatency(stream->capture.pPin, &hwFifoLatency, &dummy, &dummy);+                if (result == paNoError)+                {+                    stream->capture.pPin->hwLatency = hwFifoLatency;++                    /* Add HW latency into total input latency */+                    stream->streamRepresentation.streamInfo.inputLatency += ((hwFifoLatency / stream->capture.bytesPerFrame) / sampleRate);+                }+                else+                {+                    PA_DEBUG(("Failed to get size of FIFO hardware buffer (is set to zero)\n"));+                    stream->capture.pPin->hwLatency = 0;+                }+            }+            break;+        default:+            /* Undefined wave type!! */+            assert(0);+            result = paInternalError;+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);+            goto error;+        }+    }+    else +    {+        stream->capture.hostBuffer = 0;+    }++    if (stream->userOutputChannels > 0)+    {+        stream->streamRepresentation.streamInfo.outputLatency = stream->render.framesPerBuffer / sampleRate;++        switch (stream->render.pPin->parentFilter->devInfo.streamingType)+        {+        case Type_kWaveCyclic:+            {+                unsigned size = stream->render.noOfPackets * stream->render.framesPerBuffer * stream->render.bytesPerFrame;+                /* Allocate output device buffer */+                stream->render.hostBuffer = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, size);+                PA_DEBUG(("Output buffer allocated (size = %u)\n", size));+                if( !stream->render.hostBuffer )+                {+                    PA_DEBUG(("Cannot allocate host output buffer!\n"));+                    PaWinWDM_SetLastErrorInfo(paInsufficientMemory, "Failed to allocate output buffer");+                    result = paInsufficientMemory;+                    goto error;+                }+                stream->render.hostBufferSize = size;+                PA_DEBUG(("Output buffer start = %p (size=%u)\n",stream->render.hostBuffer, stream->render.hostBufferSize));++                stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveCyclic;+                stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveCyclic;+            }+            break;+        case Type_kWaveRT:+            {+                const DWORD dwTotalSize = 2 * stream->render.framesPerBuffer * stream->render.bytesPerFrame;+                DWORD dwRequestedSize = dwTotalSize;+                BOOL bCallMemoryBarrier = FALSE;+                ULONG hwFifoLatency = 0;+                ULONG dummy;+                result = PinGetBuffer(stream->render.pPin, (void**)&stream->render.hostBuffer, &dwRequestedSize, &bCallMemoryBarrier);+                if (!result) +                {+                    PA_DEBUG(("Output buffer start = %p, size = %u, membarrier = %u\n", stream->render.hostBuffer, dwRequestedSize, bCallMemoryBarrier));+                    if (dwRequestedSize != dwTotalSize)+                    {+                        PA_DEBUG(("Buffer length changed by driver from %u to %u !\n", dwTotalSize, dwRequestedSize));+                        /* Recalculate to what the driver has given us */+                        stream->render.framesPerBuffer = dwRequestedSize / (2 * stream->render.bytesPerFrame);+                    }+                    stream->render.hostBufferSize = dwRequestedSize;++                    if (stream->render.pPin->pinKsSubType == SubType_kPolled)+                    {+                        stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveRTPolled;+                        stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveRTPolled;+                    }+                    else+                    {+                        stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveRTEvent;+                        stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveRTEvent;+                    }++                    stream->render.pPin->fnMemBarrier = bCallMemoryBarrier ? MemoryBarrierWrite : MemoryBarrierDummy;+                }+                else +                {+                    PA_DEBUG(("Failed to get output buffer (with notification)\n"));+                    PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to get output buffer (with notification)");+                    result = paUnanticipatedHostError;+                    goto error;+                }++                /* Get latency */+                result = PinGetHwLatency(stream->render.pPin, &hwFifoLatency, &dummy, &dummy);+                if (result == paNoError)+                {+                    stream->render.pPin->hwLatency = hwFifoLatency;++                    /* Add HW latency into total output latency */+                    stream->streamRepresentation.streamInfo.outputLatency += ((hwFifoLatency / stream->render.bytesPerFrame) / sampleRate);+                }+                else+                {+                    PA_DEBUG(("Failed to get size of FIFO hardware buffer (is set to zero)\n"));+                    stream->render.pPin->hwLatency = 0;+                }+            }+            break;+        default:+            /* Undefined wave type!! */+            assert(0);+            result = paInternalError;+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);+            goto error;+        }+    }+    else +    {+        stream->render.hostBuffer = 0;+    }++    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;++    PA_DEBUG(("BytesPerInputFrame = %d\n",stream->capture.bytesPerFrame));+    PA_DEBUG(("BytesPerOutputFrame = %d\n",stream->render.bytesPerFrame));++    /* memset(stream->hostBuffer,0,size); */++    /* Abort */+    stream->eventAbort          = CreateEvent(NULL, TRUE, FALSE, NULL);+    if (stream->eventAbort == 0)+    {+        result = paInsufficientMemory;+        goto error;+    }+    stream->eventStreamStart[0] = CreateEvent(NULL, TRUE, FALSE, NULL);+    if (stream->eventStreamStart[0] == 0)+    {+        result = paInsufficientMemory;+        goto error;+    }+    stream->eventStreamStart[1] = CreateEvent(NULL, TRUE, FALSE, NULL);+    if (stream->eventStreamStart[1] == 0)+    {+        result = paInsufficientMemory;+        goto error;+    }++    if(stream->userInputChannels > 0)+    {+        const unsigned bufferSizeInBytes = stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;+        const unsigned ringBufferFrameSize = NextPowerOf2( 1024 + 2 * max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer) );++        stream->capture.events = (HANDLE*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->capture.noOfPackets * sizeof(HANDLE));+        if (stream->capture.events == NULL)+        {+            result = paInsufficientMemory;+            goto error;+        }++        stream->capture.packets = (DATAPACKET*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->capture.noOfPackets * sizeof(DATAPACKET));+        if (stream->capture.packets == NULL)+        {+            result = paInsufficientMemory;+            goto error;+        }++        switch(stream->capture.pPin->parentFilter->devInfo.streamingType)+        {+        case Type_kWaveCyclic:+            {+                /* WaveCyclic case */+                unsigned i;+                for (i = 0; i < stream->capture.noOfPackets; ++i)+                {+                    /* Set up the packets */+                    DATAPACKET *p = stream->capture.packets + i;++                    /* Record event */+                    stream->capture.events[i] = CreateEvent(NULL, TRUE, FALSE, NULL);++                    p->Signal.hEvent = stream->capture.events[i];+                    p->Header.Data = stream->capture.hostBuffer + (i*bufferSizeInBytes);+                    p->Header.FrameExtent = bufferSizeInBytes;+                    p->Header.DataUsed = 0;+                    p->Header.Size = sizeof(p->Header);+                    p->Header.PresentationTime.Numerator = 1;+                    p->Header.PresentationTime.Denominator = 1;+                }+            }+            break;+        case Type_kWaveRT:+            {+                /* Set up the "packets" */+                DATAPACKET *p = stream->capture.packets + 0;++                /* Record event: WaveRT has a single event for 2 notification per buffer */+                stream->capture.events[0] = CreateEvent(NULL, FALSE, FALSE, NULL);++                p->Header.Data = stream->capture.hostBuffer;+                p->Header.FrameExtent = bufferSizeInBytes;+                p->Header.DataUsed = 0;+                p->Header.Size = sizeof(p->Header);+                p->Header.PresentationTime.Numerator = 1;+                p->Header.PresentationTime.Denominator = 1;++                ++p;+                p->Header.Data = stream->capture.hostBuffer + bufferSizeInBytes;+                p->Header.FrameExtent = bufferSizeInBytes;+                p->Header.DataUsed = 0;+                p->Header.Size = sizeof(p->Header);+                p->Header.PresentationTime.Numerator = 1;+                p->Header.PresentationTime.Denominator = 1;++                if (stream->capture.pPin->pinKsSubType == SubType_kNotification)+                {+                    result = PinRegisterNotificationHandle(stream->capture.pPin, stream->capture.events[0]);++                    if (result != paNoError)+                    {+                        PA_DEBUG(("Failed to register capture notification handle\n"));+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to register capture notification handle");+                        result = paUnanticipatedHostError;+                        goto error;+                    }+                }++                result = PinRegisterPositionRegister(stream->capture.pPin);++                if (result != paNoError)+                {+                    unsigned long pos = 0xdeadc0de;+                    PA_DEBUG(("Failed to register capture position register, using PinGetAudioPositionViaIOCTL\n"));+                    stream->capture.pPin->fnAudioPosition = PinGetAudioPositionViaIOCTL;+                    /* Test position function */+                    result = (stream->capture.pPin->fnAudioPosition)(stream->capture.pPin, &pos);+                    if (result != paNoError || pos != 0x0)+                    {+                        PA_DEBUG(("Failed to read capture position register (IOCTL)\n"));+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to read capture position register (IOCTL)");+                        result = paUnanticipatedHostError;+                        goto error;+                    }                +                }+                else+                {+                    stream->capture.pPin->fnAudioPosition = PinGetAudioPositionDirect;+                }+            }+            break;+        default:+            /* Undefined wave type!! */+            assert(0);+            result = paInternalError;+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);+            goto error;+        }++        /* Setup the input ring buffer here */+        stream->ringBufferData = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, ringBufferFrameSize * stream->capture.bytesPerFrame);+        if (stream->ringBufferData == NULL)+        {+            result = paInsufficientMemory;+            goto error;+        }+        PaUtil_InitializeRingBuffer(&stream->ringBuffer, stream->capture.bytesPerFrame, ringBufferFrameSize, stream->ringBufferData);+    }+    if(stream->userOutputChannels > 0)+    {+        const unsigned bufferSizeInBytes = stream->render.framesPerBuffer * stream->render.bytesPerFrame;++        stream->render.events = (HANDLE*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->render.noOfPackets * sizeof(HANDLE));+        if (stream->render.events == NULL)+        {+            result = paInsufficientMemory;+            goto error;+        }++        stream->render.packets = (DATAPACKET*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->render.noOfPackets * sizeof(DATAPACKET));+        if (stream->render.packets == NULL)+        {+            result = paInsufficientMemory;+            goto error;+        }++        switch(stream->render.pPin->parentFilter->devInfo.streamingType)+        {+        case Type_kWaveCyclic:+            {+                /* WaveCyclic case */+                unsigned i;+                for (i = 0; i < stream->render.noOfPackets; ++i)+                {+                    /* Set up the packets */+                    DATAPACKET *p = stream->render.packets + i;++                    /* Playback event */+                    stream->render.events[i] = CreateEvent(NULL, TRUE, FALSE, NULL);++                    /* In this case, we just use the packets as ptr to the device buffer */+                    p->Signal.hEvent = stream->render.events[i];+                    p->Header.Data = stream->render.hostBuffer + (i*bufferSizeInBytes);+                    p->Header.FrameExtent = bufferSizeInBytes;+                    p->Header.DataUsed = bufferSizeInBytes;+                    p->Header.Size = sizeof(p->Header);+                    p->Header.PresentationTime.Numerator = 1;+                    p->Header.PresentationTime.Denominator = 1;+                }+            }+            break;+        case Type_kWaveRT:+            {+                /* WaveRT case */++                /* Set up the "packets" */+                DATAPACKET *p = stream->render.packets;++                /* The only playback event */+                stream->render.events[0] = CreateEvent(NULL, FALSE, FALSE, NULL);++                /* In this case, we just use the packets as ptr to the device buffer */+                p->Header.Data = stream->render.hostBuffer;+                p->Header.FrameExtent = stream->render.framesPerBuffer*stream->render.bytesPerFrame;+                p->Header.DataUsed = stream->render.framesPerBuffer*stream->render.bytesPerFrame;+                p->Header.Size = sizeof(p->Header);+                p->Header.PresentationTime.Numerator = 1;+                p->Header.PresentationTime.Denominator = 1;++                ++p;+                p->Header.Data = stream->render.hostBuffer + stream->render.framesPerBuffer*stream->render.bytesPerFrame;+                p->Header.FrameExtent = stream->render.framesPerBuffer*stream->render.bytesPerFrame;+                p->Header.DataUsed = stream->render.framesPerBuffer*stream->render.bytesPerFrame;+                p->Header.Size = sizeof(p->Header);+                p->Header.PresentationTime.Numerator = 1;+                p->Header.PresentationTime.Denominator = 1;++                if (stream->render.pPin->pinKsSubType == SubType_kNotification)+                {+                    result = PinRegisterNotificationHandle(stream->render.pPin, stream->render.events[0]);++                    if (result != paNoError)+                    {+                        PA_DEBUG(("Failed to register rendering notification handle\n"));+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to register rendering notification handle");+                        result = paUnanticipatedHostError;+                        goto error;+                    }+                }++                result = PinRegisterPositionRegister(stream->render.pPin);++                if (result != paNoError)+                {+                    unsigned long pos = 0xdeadc0de;+                    PA_DEBUG(("Failed to register rendering position register, using PinGetAudioPositionViaIOCTL\n"));+                    stream->render.pPin->fnAudioPosition = PinGetAudioPositionViaIOCTL;+                    /* Test position function */+                    result = (stream->render.pPin->fnAudioPosition)(stream->render.pPin, &pos);+                    if (result != paNoError || pos != 0x0)+                    {+                        PA_DEBUG(("Failed to read render position register (IOCTL)\n"));+                        PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to read render position register (IOCTL)");+                        result = paUnanticipatedHostError;+                        goto error;+                    }+                }+                else+                {+                    stream->render.pPin->fnAudioPosition = PinGetAudioPositionDirect;+                }+            }+            break;+        default:+            /* Undefined wave type!! */+            assert(0);+            result = paInternalError;+            PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);+            goto error;+        }+    }++    stream->streamStarted = 0;+    stream->streamActive = 0;+    stream->streamStop = 0;+    stream->streamAbort = 0;+    stream->streamFlags = streamFlags;+    stream->oldProcessPriority = REALTIME_PRIORITY_CLASS;++    /* Increase ref count on filters in use, so that a CommitDeviceInfos won't delete them */+    if (stream->capture.pPin != 0)+    {+        FilterAddRef(stream->capture.pPin->parentFilter);+    }+    if (stream->render.pPin != 0)+    {+        FilterAddRef(stream->render.pPin->parentFilter);+    }++    /* Ok, now update our host API specific stream info */+    if (stream->userInputChannels)+    {+        PaWinWdmDeviceInfo *pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];++        stream->hostApiStreamInfo.input.device = Pa_HostApiDeviceIndexToDeviceIndex(Pa_HostApiTypeIdToHostApiIndex(paWDMKS), inputParameters->device);+        stream->hostApiStreamInfo.input.channels = stream->deviceInputChannels;+        stream->hostApiStreamInfo.input.muxNodeId = -1;+        if (stream->capture.pPin->inputs)+        {+            stream->hostApiStreamInfo.input.muxNodeId = stream->capture.pPin->inputs[pDeviceInfo->muxPosition]->muxNodeId;+        }+        stream->hostApiStreamInfo.input.endpointPinId = pDeviceInfo->endpointPinId;+        stream->hostApiStreamInfo.input.framesPerHostBuffer = stream->capture.framesPerBuffer;+        stream->hostApiStreamInfo.input.streamingSubType = stream->capture.pPin->pinKsSubType;+    }+    else+    {+        stream->hostApiStreamInfo.input.device = paNoDevice;+    }+    if (stream->userOutputChannels)+    {+        stream->hostApiStreamInfo.output.device = Pa_HostApiDeviceIndexToDeviceIndex(Pa_HostApiTypeIdToHostApiIndex(paWDMKS), outputParameters->device);+        stream->hostApiStreamInfo.output.channels = stream->deviceOutputChannels;+        stream->hostApiStreamInfo.output.framesPerHostBuffer = stream->render.framesPerBuffer;+        stream->hostApiStreamInfo.output.endpointPinId = stream->render.pPin->endpointPinId;+        stream->hostApiStreamInfo.output.streamingSubType = stream->render.pPin->pinKsSubType;+    }+    else+    {+        stream->hostApiStreamInfo.output.device = paNoDevice;+    }+    /*stream->streamRepresentation.streamInfo.hostApiTypeId = paWDMKS;+    stream->streamRepresentation.streamInfo.hostApiSpecificStreamInfo = &stream->hostApiStreamInfo;*/+    stream->streamRepresentation.streamInfo.structVersion = 2;++    *s = (PaStream*)stream;++    PA_LOGL_;+    return result;++occupied:+    /* Ok, someone else is hogging the pin, bail out */+    assert (result == paDeviceUnavailable);+    PaWinWDM_SetLastErrorInfo(result, "Device is occupied");++error:+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );++    CloseStreamEvents(stream);++    if (stream->allocGroup)+    {+        PaUtil_FreeAllAllocations(stream->allocGroup);+        PaUtil_DestroyAllocationGroup(stream->allocGroup);+        stream->allocGroup = 0;+    }++    if(stream->render.pPin)+        PinClose(stream->render.pPin);+    if(stream->capture.pPin)+        PinClose(stream->capture.pPin);++    PaUtil_FreeMemory( stream );++    PA_LOGL_;+    return result;+}++/*+When CloseStream() is called, the multi-api layer ensures that+the stream has already been stopped or aborted.+*/+static PaError CloseStream( PaStream* s )+{+    PaError result = paNoError;+    PaWinWdmStream *stream = (PaWinWdmStream*)s;++    PA_LOGE_;++    assert(!stream->streamStarted);+    assert(!stream->streamActive);++    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );++    CloseStreamEvents(stream);++    if (stream->allocGroup)+    {+        PaUtil_FreeAllAllocations(stream->allocGroup);+        PaUtil_DestroyAllocationGroup(stream->allocGroup);+        stream->allocGroup = 0;+    }++    if(stream->render.pPin)+    {+        PinClose(stream->render.pPin);+    }+    if(stream->capture.pPin)+    {+        PinClose(stream->capture.pPin);+    }++    if (stream->render.pPin)+    {+        FilterFree(stream->render.pPin->parentFilter);+    }+    if (stream->capture.pPin)+    {+        FilterFree(stream->capture.pPin->parentFilter);+    }++    PaUtil_FreeMemory( stream );++    PA_LOGL_;+    return result;+}++/*+Write the supplied packet to the pin+Asynchronous+Should return paNoError on success+*/+static PaError PinWrite(HANDLE h, DATAPACKET* p)+{+    PaError result = paNoError;+    unsigned long cbReturned = 0;+    BOOL fRes = DeviceIoControl(h,+        IOCTL_KS_WRITE_STREAM,+        NULL,+        0,+        &p->Header,+        p->Header.Size,+        &cbReturned,+        &p->Signal);+    if (!fRes)+    {+        unsigned long error = GetLastError();+        if (error != ERROR_IO_PENDING)+        {+            result = paInternalError;+        }+    }+    return result;+}++/*+Read to the supplied packet from the pin+Asynchronous+Should return paNoError on success+*/+static PaError PinRead(HANDLE h, DATAPACKET* p)+{+    PaError result = paNoError;+    unsigned long cbReturned = 0;+    BOOL fRes = DeviceIoControl(h,+        IOCTL_KS_READ_STREAM,+        NULL,+        0,+        &p->Header,+        p->Header.Size,+        &cbReturned,+        &p->Signal);+    if (!fRes)+    {+        unsigned long error = GetLastError();+        if (error != ERROR_IO_PENDING)+        {+            result = paInternalError;+        }+    }+    return result;+}++/*+Copy the first interleaved channel of 16 bit data to the other channels+*/+static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples)+{+    unsigned short* data = (unsigned short*)buffer;+    int channel;+    unsigned short sourceSample;+    while( samples-- )+    {+        sourceSample = *data++;+        channel = channels-1;+        while( channel-- )+        {+            *data++ = sourceSample;+        }+    }+}++/*+Copy the first interleaved channel of 24 bit data to the other channels+*/+static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples)+{+    unsigned char* data = (unsigned char*)buffer;+    int channel;+    unsigned char sourceSample[3];+    while( samples-- )+    {+        sourceSample[0] = data[0];+        sourceSample[1] = data[1];+        sourceSample[2] = data[2];+        data += 3;+        channel = channels-1;+        while( channel-- )+        {+            data[0] = sourceSample[0];+            data[1] = sourceSample[1];+            data[2] = sourceSample[2];+            data += 3;+        }+    }+}++/*+Copy the first interleaved channel of 32 bit data to the other channels+*/+static void DuplicateFirstChannelInt32(void* buffer, int channels, int samples)+{+    unsigned long* data = (unsigned long*)buffer;+    int channel;+    unsigned long sourceSample;+    while( samples-- )+    {+        sourceSample = *data++;+        channel = channels-1;+        while( channel-- )+        {+            *data++ = sourceSample;+        }+    }+}++/*+Increase the priority of the calling thread to RT +*/+static HANDLE BumpThreadPriority() +{+    HANDLE hThread = GetCurrentThread();+    DWORD dwTask = 0;+    HANDLE hAVRT = NULL;++    /* If we have access to AVRT.DLL (Vista and later), use it */+    if (paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics != NULL) +    {+        hAVRT = paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics("Pro Audio", &dwTask);+        if (hAVRT != NULL && hAVRT != INVALID_HANDLE_VALUE) +        {+            BOOL bret = paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority(hAVRT, PA_AVRT_PRIORITY_CRITICAL);+            if (!bret)+            {+                PA_DEBUG(("Set mm thread prio to critical failed!\n"));+            }+            else+            {+                return hAVRT;+            }+        }+        else+        {+            PA_DEBUG(("Set mm thread characteristic to 'Pro Audio' failed, reverting to SetThreadPriority\n"));+        }+    }++    /* For XP and earlier, or if AvSetMmThreadCharacteristics fails (MMCSS disabled ?) */+    if (timeBeginPeriod(1) != TIMERR_NOERROR) {+        PA_DEBUG(("timeBeginPeriod(1) failed!\n"));+    }++    if (!SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL)) {+        PA_DEBUG(("SetThreadPriority failed!\n"));+    }++    return hAVRT;+}++/*+Decrease the priority of the calling thread to normal+*/+static void DropThreadPriority(HANDLE hAVRT)+{+    HANDLE hThread = GetCurrentThread();++    if (hAVRT != NULL) +    {+        paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority(hAVRT, PA_AVRT_PRIORITY_NORMAL);+        paWinWDMKSAvRtEntryPoints.AvRevertMmThreadCharacteristics(hAVRT);+        return;+    }++    SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL);+    timeEndPeriod(1);+}++static PaError PreparePinForStart(PaWinWdmPin* pin)+{+    PaError result;+    result = PinSetState(pin, KSSTATE_ACQUIRE);+    if (result != paNoError)+    {+        goto error;+    }+    result = PinSetState(pin, KSSTATE_PAUSE);+    if (result != paNoError)+    {+        goto error;+    }+    return result;++error:+    PinSetState(pin, KSSTATE_STOP);+    return result;+}++static PaError PreparePinsForStart(PaProcessThreadInfo* pInfo)+{+    PaError result = paNoError;+    /* Submit buffers */+    if (pInfo->stream->capture.pPin)+    {+        if ((result = PreparePinForStart(pInfo->stream->capture.pPin)) != paNoError)+        {+            goto error;+        }++        if (pInfo->stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)+        {+            unsigned i;+            for(i=0; i < pInfo->stream->capture.noOfPackets; ++i)+            {+                if ((result = PinRead(pInfo->stream->capture.pPin->handle, pInfo->stream->capture.packets + i)) != paNoError)+                {+                    goto error;+                }+                ++pInfo->pending;+            }+        }+        else+        {+            pInfo->pending = 2;+        }+    }++    if(pInfo->stream->render.pPin)+    {+        if ((result = PreparePinForStart(pInfo->stream->render.pPin)) != paNoError)+        {+            goto error;+        }++        pInfo->priming += pInfo->stream->render.noOfPackets;+        ++pInfo->pending;+        SetEvent(pInfo->stream->render.events[0]);+        if (pInfo->stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic) +        {+            unsigned i;+            for(i=1; i < pInfo->stream->render.noOfPackets; ++i)+            {+                SetEvent(pInfo->stream->render.events[i]);+                ++pInfo->pending;+            }+        }+    }++error:+    PA_DEBUG(("PreparePinsForStart = %d\n", result));+    return result;+}++static PaError StartPin(PaWinWdmPin* pin)+{+    return PinSetState(pin, KSSTATE_RUN);+}++static PaError StartPins(PaProcessThreadInfo* pInfo)+{+    PaError result = paNoError;+    /* Start the pins as synced as possible */+    if (pInfo->stream->capture.pPin)+    {+        result = StartPin(pInfo->stream->capture.pPin);+    }+    if(pInfo->stream->render.pPin)+    {+        result = StartPin(pInfo->stream->render.pPin);+    }+    PA_DEBUG(("StartPins = %d\n", result));+    return result;+}+++static PaError StopPin(PaWinWdmPin* pin)+{+    PinSetState(pin, KSSTATE_PAUSE);+    PinSetState(pin, KSSTATE_STOP);+    return paNoError;+}+++static PaError StopPins(PaProcessThreadInfo* pInfo)+{+    PaError result = paNoError;+    if(pInfo->stream->render.pPin)+    {+        StopPin(pInfo->stream->render.pPin);+    }+    if(pInfo->stream->capture.pPin)+    {+        StopPin(pInfo->stream->capture.pPin);+    }+    return result;+}++typedef void (*TSetInputFrameCount)(PaUtilBufferProcessor*, unsigned long);+typedef void (*TSetInputChannel)(PaUtilBufferProcessor*, unsigned int, void *, unsigned int);+static const TSetInputFrameCount fnSetInputFrameCount[2] = { PaUtil_SetInputFrameCount, PaUtil_Set2ndInputFrameCount };+static const TSetInputChannel fnSetInputChannel[2] = { PaUtil_SetInputChannel, PaUtil_Set2ndInputChannel };++static PaError PaDoProcessing(PaProcessThreadInfo* pInfo)+{+    PaError result = paNoError;+    int i, framesProcessed = 0, doChannelCopy = 0;+    ring_buffer_size_t inputFramesAvailable = PaUtil_GetRingBufferReadAvailable(&pInfo->stream->ringBuffer);++    /* Do necessary buffer processing (which will invoke user callback if necessary) */+    if (pInfo->cbResult == paContinue &&+        (pInfo->renderHead != pInfo->renderTail || inputFramesAvailable))+    {+        unsigned processFullDuplex = pInfo->stream->capture.pPin && pInfo->stream->render.pPin && (!pInfo->priming);++        PA_HP_TRACE((pInfo->stream->hLog, "DoProcessing: InputFrames=%u", inputFramesAvailable));++        PaUtil_BeginCpuLoadMeasurement( &pInfo->stream->cpuLoadMeasurer );++        pInfo->ti.currentTime = PaUtil_GetTime();++        PaUtil_BeginBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->ti, pInfo->underover);+        pInfo->underover = 0; /* Reset the (under|over)flow status */++        if (pInfo->renderTail != pInfo->renderHead)+        {+            DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;++            assert(packet != 0);+            assert(packet->Header.Data != 0);++            PaUtil_SetOutputFrameCount(&pInfo->stream->bufferProcessor, pInfo->stream->render.framesPerBuffer);++            for(i=0;i<pInfo->stream->userOutputChannels;i++)+            {+                /* Only write the user output channels. Leave the rest blank */+                PaUtil_SetOutputChannel(&pInfo->stream->bufferProcessor,+                    i,+                    ((unsigned char*)(packet->Header.Data))+(i*pInfo->stream->render.bytesPerSample),+                    pInfo->stream->deviceOutputChannels);+            }++            /* We will do a copy to the other channels after the data has been written */+            doChannelCopy = ( pInfo->stream->userOutputChannels == 1 );+        }++        if (inputFramesAvailable && (!pInfo->stream->userOutputChannels || inputFramesAvailable >= (int)pInfo->stream->render.framesPerBuffer))+        {+            unsigned wrapCntr = 0;+            void* data[2] = {0};+            ring_buffer_size_t size[2] = {0};++            /* If full-duplex, we just extract output buffer number of frames */+            if (pInfo->stream->userOutputChannels)+            {+                inputFramesAvailable = min(inputFramesAvailable, (int)pInfo->stream->render.framesPerBuffer);+            }++            inputFramesAvailable = PaUtil_GetRingBufferReadRegions(&pInfo->stream->ringBuffer,+                inputFramesAvailable,+                &data[0],+                &size[0],+                &data[1],+                &size[1]);++            for (wrapCntr = 0; wrapCntr < 2; ++wrapCntr)+            {+                if (size[wrapCntr] == 0)+                    break;++                fnSetInputFrameCount[wrapCntr](&pInfo->stream->bufferProcessor, size[wrapCntr]);+                for(i=0;i<pInfo->stream->userInputChannels;i++)+                {+                    /* Only read as many channels as the user wants */+                    fnSetInputChannel[wrapCntr](&pInfo->stream->bufferProcessor,+                        i,+                        ((unsigned char*)(data[wrapCntr]))+(i*pInfo->stream->capture.bytesPerSample),+                        pInfo->stream->deviceInputChannels);+                }+            }+        }+        else+        {+            /* We haven't consumed anything from the ring buffer... */+            inputFramesAvailable = 0;+            /* If we have full-duplex, this is at startup, so mark no-input! */+            if (pInfo->stream->userOutputChannels>0 && pInfo->stream->userInputChannels>0)+            {+                PA_HP_TRACE((pInfo->stream->hLog, "Input startup, marking no input."));+                PaUtil_SetNoInput(&pInfo->stream->bufferProcessor);+            }+        }++        if (processFullDuplex) /* full duplex */+        {+            /* Only call the EndBufferProcessing function when the total input frames == total output frames */+            const unsigned long totalInputFrameCount = pInfo->stream->bufferProcessor.hostInputFrameCount[0] + pInfo->stream->bufferProcessor.hostInputFrameCount[1];+            const unsigned long totalOutputFrameCount = pInfo->stream->bufferProcessor.hostOutputFrameCount[0] + pInfo->stream->bufferProcessor.hostOutputFrameCount[1];++            if(totalInputFrameCount == totalOutputFrameCount && totalOutputFrameCount != 0)+            {+                framesProcessed = PaUtil_EndBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->cbResult);+            }+            else+            {+                framesProcessed = 0;+            }+        }+        else +        {+            framesProcessed = PaUtil_EndBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->cbResult);+        }++        PA_HP_TRACE((pInfo->stream->hLog, "Frames processed: %u %s", framesProcessed, (pInfo->priming ? "(priming)":"")));++        if( doChannelCopy )+        {+            DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;+            /* Copy the first output channel to the other channels */+            switch (pInfo->stream->render.bytesPerSample)+            {+            case 2:+                DuplicateFirstChannelInt16(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);+                break;+            case 3:+                DuplicateFirstChannelInt24(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);+                break;+            case 4:+                DuplicateFirstChannelInt32(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);+                break;+            default:+                assert(0); /* Unsupported format! */+                break;+            }+        }+        PaUtil_EndCpuLoadMeasurement( &pInfo->stream->cpuLoadMeasurer, framesProcessed );++        if (inputFramesAvailable)+        {+            PaUtil_AdvanceRingBufferReadIndex(&pInfo->stream->ringBuffer, inputFramesAvailable);+        }++        if (pInfo->renderTail != pInfo->renderHead)+        {+            if (!pInfo->stream->streamStop)+            {+                result = pInfo->stream->render.pPin->fnSubmitHandler(pInfo, pInfo->renderTail);+                if (result != paNoError)+                {+                    PA_HP_TRACE((pInfo->stream->hLog, "Capture submit handler failed with result %d", result));+                    return result;+                }+            }+            pInfo->renderTail++;+            if (!pInfo->pinsStarted && pInfo->priming == 0)+            {+                /* We start the pins here to allow "prime time" */+                if ((result = StartPins(pInfo)) == paNoError)+                {+                    PA_HP_TRACE((pInfo->stream->hLog, "Starting pins!"));+                    pInfo->pinsStarted = 1;+                }+            }+        }+    }++    return result;+}++static VOID CALLBACK TimerAPCWaveRTPolledMode(+    LPVOID lpArgToCompletionRoutine,+    DWORD dwTimerLowValue,+    DWORD dwTimerHighValue)+{+    HANDLE* pHandles = (HANDLE*)lpArgToCompletionRoutine;+    if (pHandles[0]) SetEvent(pHandles[0]);+    if (pHandles[1]) SetEvent(pHandles[1]);+}++static DWORD GetCurrentTimeInMillisecs()+{+    return timeGetTime();+}++PA_THREAD_FUNC ProcessingThread(void* pParam)+{+    PaError result = paNoError;+    HANDLE hAVRT = NULL;+    HANDLE hTimer = NULL;+    HANDLE *handleArray = NULL;+    HANDLE timerEventHandles[2] = {0};+    unsigned noOfHandles = 0;+    unsigned captureEvents = 0;+    unsigned renderEvents = 0;+    unsigned timerPeriod = 0;+    DWORD timeStamp[2] = {0};++    PaProcessThreadInfo info;+    memset(&info, 0, sizeof(PaProcessThreadInfo));+    info.stream = (PaWinWdmStream*)pParam;++    info.stream->threadResult = paNoError;++    PA_LOGE_;++    info.ti.inputBufferAdcTime = 0.0;+    info.ti.currentTime = 0.0;+    info.ti.outputBufferDacTime = 0.0;++    PA_DEBUG(("In  buffer len: %.3f ms\n",(2000*info.stream->capture.framesPerBuffer) / info.stream->streamRepresentation.streamInfo.sampleRate));+    PA_DEBUG(("Out buffer len: %.3f ms\n",(2000*info.stream->render.framesPerBuffer) / info.stream->streamRepresentation.streamInfo.sampleRate));+    info.timeout = (DWORD)max(+        (2000*info.stream->render.framesPerBuffer/info.stream->streamRepresentation.streamInfo.sampleRate + 0.5),+        (2000*info.stream->capture.framesPerBuffer/info.stream->streamRepresentation.streamInfo.sampleRate + 0.5));+    info.timeout = max(info.timeout*8, 100);+    timerPeriod = info.timeout;+    PA_DEBUG(("Timeout = %ld ms\n",info.timeout));++    /* Allocate handle array */+    handleArray = (HANDLE*)PaUtil_AllocateMemory((info.stream->capture.noOfPackets + info.stream->render.noOfPackets + 1) * sizeof(HANDLE));++    /* Setup handle array for WFMO */+    if (info.stream->capture.pPin != 0)+    {+        handleArray[noOfHandles++] = info.stream->capture.events[0];+        if (info.stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)+        {+            unsigned i;+            for(i=1; i < info.stream->capture.noOfPackets; ++i)+            {+                handleArray[noOfHandles++] = info.stream->capture.events[i];+            }+        }+        captureEvents = noOfHandles;+        renderEvents = noOfHandles;+    }++    if (info.stream->render.pPin != 0)+    {+        handleArray[noOfHandles++] = info.stream->render.events[0];+        if (info.stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)+        {+            unsigned i;+            for(i=1; i < info.stream->render.noOfPackets; ++i)+            {+                handleArray[noOfHandles++] = info.stream->render.events[i];+            }+        }+        renderEvents = noOfHandles;+    }+    handleArray[noOfHandles++] = info.stream->eventAbort;+    assert(noOfHandles <= (info.stream->capture.noOfPackets + info.stream->render.noOfPackets + 1));++    /* Prepare render and capture pins */+    if ((result = PreparePinsForStart(&info)) != paNoError) +    {+        PA_DEBUG(("Failed to prepare device(s)!\n"));+        goto error;+    }++    /* Init high speed logger */+    if (PaUtil_InitializeHighSpeedLog(&info.stream->hLog, 1000000) != paNoError)+    {+        PA_DEBUG(("Failed to init high speed logger!\n"));+        goto error;+    }++    /* Heighten priority here */+    hAVRT = BumpThreadPriority();++    /* If input only, we start the pins immediately */+    if (info.stream->render.pPin == 0)+    {+        if ((result = StartPins(&info)) != paNoError)+        {+            PA_DEBUG(("Failed to start device(s)!\n"));+            goto error;+        }+        info.pinsStarted = 1;+    }++    /* Handle WaveRT polled mode */+    {+        const unsigned fs = (unsigned)info.stream->streamRepresentation.streamInfo.sampleRate;+        if (info.stream->capture.pPin != 0 && info.stream->capture.pPin->pinKsSubType == SubType_kPolled)+        {+            timerEventHandles[0] = info.stream->capture.events[0];+            timerPeriod = min(timerPeriod, (1000*info.stream->capture.framesPerBuffer)/fs);+        }++        if (info.stream->render.pPin != 0 && info.stream->render.pPin->pinKsSubType == SubType_kPolled)+        {+            timerEventHandles[1] = info.stream->render.events[0];+            timerPeriod = min(timerPeriod, (1000*info.stream->render.framesPerBuffer)/fs);+        }++        if (timerEventHandles[0] || timerEventHandles[1])+        {+            LARGE_INTEGER dueTime = {0};++            timerPeriod=max(timerPeriod/5,1);+            PA_DEBUG(("Timer event handles=0x%04X,0x%04X period=%u ms", timerEventHandles[0], timerEventHandles[1], timerPeriod));+            hTimer = CreateWaitableTimer(0, FALSE, NULL);+            if (hTimer == NULL)+            {+                result = paUnanticipatedHostError;+                goto error;+            }+            /* invoke first timeout immediately */+            if (!SetWaitableTimer(hTimer, &dueTime, timerPeriod, TimerAPCWaveRTPolledMode, timerEventHandles, FALSE))+            {+                result = paUnanticipatedHostError;+                goto error;+            }+            PA_DEBUG(("Waitable timer started, period = %u ms\n", timerPeriod));+        }+    }++    /* Mark stream as active */+    info.stream->streamActive = 1;+    info.stream->threadResult = paNoError;++    /* Up and running... */+    SetEvent(info.stream->eventStreamStart[StreamStart_kOk]);++    /* Take timestamp here */+    timeStamp[0] = timeStamp[1] = GetCurrentTimeInMillisecs();++    while(!info.stream->streamAbort)+    {+        unsigned doProcessing = 1;+        unsigned wait = WaitForMultipleObjects(noOfHandles, handleArray, FALSE, 0);+        unsigned eventSignalled = wait - WAIT_OBJECT_0;+        DWORD dwCurrentTime = 0;++        if (wait == WAIT_FAILED) +        {+            PA_DEBUG(("Wait failed = %ld! \n",wait));+            break;+        }+        if (wait == WAIT_TIMEOUT)+        {+            wait = WaitForMultipleObjectsEx(noOfHandles, handleArray, FALSE, 50, TRUE);+            eventSignalled = wait - WAIT_OBJECT_0;+        }+        else+        {+            if (eventSignalled < captureEvents)+            {+                if (PaUtil_GetRingBufferWriteAvailable(&info.stream->ringBuffer) == 0)+                {+                    PA_HP_TRACE((info.stream->hLog, "!!!!! Input overflow !!!!!"));+                    info.underover |= paInputOverflow;+                }+            }+            else if (eventSignalled < renderEvents)+            {+                if (!info.priming && info.renderHead - info.renderTail > 1)+                {+                    PA_HP_TRACE((info.stream->hLog, "!!!!! Output underflow !!!!!"));+                    info.underover |= paOutputUnderflow;+                }+            }+        }++        /* Get event time */+        dwCurrentTime = GetCurrentTimeInMillisecs();++        /* Since we can mix capture/render devices between WaveCyclic, WaveRT polled and WaveRT notification (3x3 combinations), +        we can't rely on the timeout of WFMO to check for device timeouts, we need to keep tally. */+        if (info.stream->capture.pPin && (dwCurrentTime - timeStamp[0]) >= info.timeout)+        {+            PA_DEBUG(("Timeout for capture device (%u ms)!", info.timeout, (dwCurrentTime - timeStamp[0])));+            result = paTimedOut;+            break;+        }+        if (info.stream->render.pPin && (dwCurrentTime - timeStamp[1]) >= info.timeout)+        {+            PA_DEBUG(("Timeout for render device (%u ms)!", info.timeout, (dwCurrentTime - timeStamp[1])));+            result = paTimedOut;+            break;+        }++        if (wait == WAIT_IO_COMPLETION)+        {+            /* Waitable timer has fired! */+            PA_HP_TRACE((info.stream->hLog, "WAIT_IO_COMPLETION"));+            continue;+        }++        if (wait == WAIT_TIMEOUT)+        {+            continue;+        }+        else+        {+            if (eventSignalled < captureEvents)+            {+                if (info.stream->capture.pPin->fnEventHandler(&info, eventSignalled) == paNoError)+                {+                    timeStamp[0] = dwCurrentTime;++                    /* Since we use the ring buffer, we can submit the buffers directly */+                    if (!info.stream->streamStop)+                    {+                        result = info.stream->capture.pPin->fnSubmitHandler(&info, info.captureTail);+                        if (result != paNoError)+                        {+                            PA_HP_TRACE((info.stream->hLog, "Capture submit handler failed with result %d", result));+                            break;+                        }+                    }+                    ++info.captureTail;+                    /* If full-duplex, let _only_ render event trigger processing. We still need the stream stop+                    handling working, so let that be processed anyways... */+                    if (info.stream->userOutputChannels > 0)+                    {+                        doProcessing = 0;+                    }+                }+            }+            else if (eventSignalled < renderEvents)+            {+                timeStamp[1] = dwCurrentTime;+                eventSignalled -= captureEvents;+                info.stream->render.pPin->fnEventHandler(&info, eventSignalled);+            }+            else+            {+                assert(info.stream->streamAbort);+                PA_HP_TRACE((info.stream->hLog, "Stream abort!"));+                continue;+            }+        }++        /* Handle processing */+        if (doProcessing)+        {+            result = PaDoProcessing(&info);+            if (result != paNoError)+            {+                PA_HP_TRACE((info.stream->hLog, "PaDoProcessing failed!"));+                break;+            }+        }++        if(info.stream->streamStop && info.cbResult != paComplete)+        {+            PA_HP_TRACE((info.stream->hLog, "Stream stop! pending=%d",info.pending));+            info.cbResult = paComplete; /* Stop, but play remaining buffers */+        }++        if(info.pending<=0)+        {+            PA_HP_TRACE((info.stream->hLog, "pending==0 finished..."));+            break;+        }+        if((!info.stream->render.pPin)&&(info.cbResult!=paContinue))+        {+            PA_HP_TRACE((info.stream->hLog, "record only cbResult=%d...",info.cbResult));+            break;+        }+    }++    PA_DEBUG(("Finished processing loop\n"));++    info.stream->threadResult = result;+    goto bailout;++error:+    PA_DEBUG(("Error starting processing thread\n"));+    /* Set the "error" event together with result */+    info.stream->threadResult = result;+    SetEvent(info.stream->eventStreamStart[StreamStart_kFailed]);++bailout:+    if (hTimer)+    {+        PA_DEBUG(("Waitable timer stopped\n", timerPeriod));+        CancelWaitableTimer(hTimer);+        CloseHandle(hTimer);+        hTimer = 0;+    }++    if (info.pinsStarted)+    {+        StopPins(&info);+    }++    /* Lower prio here */+    DropThreadPriority(hAVRT);++    if (handleArray != NULL)+    {+        PaUtil_FreeMemory(handleArray);+    }++#if PA_TRACE_REALTIME_EVENTS+    if (info.stream->hLog)+    {+        PA_DEBUG(("Dumping highspeed trace...\n"));+        PaUtil_DumpHighSpeedLog(info.stream->hLog, "hp_trace.log");+        PaUtil_DiscardHighSpeedLog(info.stream->hLog);+        info.stream->hLog = 0;+    }+#endif+    info.stream->streamActive = 0;++    if((!info.stream->streamStop)&&(!info.stream->streamAbort))+    {+        /* Invoke the user stream finished callback */+        /* Only do it from here if not being stopped/aborted by user */+        if( info.stream->streamRepresentation.streamFinishedCallback != 0 )+            info.stream->streamRepresentation.streamFinishedCallback( info.stream->streamRepresentation.userData );+    }+    info.stream->streamStop = 0;+    info.stream->streamAbort = 0;++    PA_LOGL_;+    return 0;+}+++static PaError StartStream( PaStream *s )+{+    PaError result = paNoError;+    PaWinWdmStream *stream = (PaWinWdmStream*)s;++    PA_LOGE_;++    if (stream->streamThread != NULL)+    {+        return paStreamIsNotStopped;+    }++    stream->streamStop = 0;+    stream->streamAbort = 0;++    ResetStreamEvents(stream);++    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );++    stream->oldProcessPriority = GetPriorityClass(GetCurrentProcess());+    /* Uncomment the following line to enable dynamic boosting of the process+    * priority to real time for best low latency support+    * Disabled by default because RT processes can easily block the OS */+    /*ret = SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS);+    PA_DEBUG(("Class ret = %d;",ret));*/++    stream->streamThread = CREATE_THREAD_FUNCTION (NULL, 0, ProcessingThread, stream, CREATE_SUSPENDED, NULL);+    if(stream->streamThread == NULL)+    {+        result = paInsufficientMemory;+        goto end;+    }+    ResumeThread(stream->streamThread);++    switch (WaitForMultipleObjects(2, stream->eventStreamStart, FALSE, 5000))+    {+    case WAIT_OBJECT_0 + StreamStart_kOk:+        PA_DEBUG(("Processing thread started!\n"));+        result = paNoError;+        /* streamActive is set in processing thread */+        stream->streamStarted = 1;+        break;+    case WAIT_OBJECT_0 + StreamStart_kFailed:+        PA_DEBUG(("Processing thread start failed! (result=%d)\n", stream->threadResult));+        result = stream->threadResult;+        /* Wait for the stream to really exit */+        WaitForSingleObject(stream->streamThread, 200);+        CloseHandle(stream->streamThread);+        stream->streamThread = 0;+        break;+    case WAIT_TIMEOUT:+    default:+        result = paTimedOut;+        PaWinWDM_SetLastErrorInfo(result, "Failed to start processing thread (timeout)!");+        break;+    }++end:+    PA_LOGL_;+    return result;+}+++static PaError StopStream( PaStream *s )+{+    PaError result = paNoError;+    PaWinWdmStream *stream = (PaWinWdmStream*)s;+    BOOL doCb = FALSE;++    PA_LOGE_;++    if(stream->streamActive)+    {+        DWORD dwExitCode;+        doCb = TRUE;+        stream->streamStop = 1;+        if (GetExitCodeThread(stream->streamThread, &dwExitCode) && dwExitCode == STILL_ACTIVE)+        {+            if (WaitForSingleObject(stream->streamThread, INFINITE) != WAIT_OBJECT_0)+            {+                PA_DEBUG(("StopStream: stream thread terminated\n"));+                TerminateThread(stream->streamThread, -1);+                result = paTimedOut;+            }+        }+        else+        {+            PA_DEBUG(("StopStream: GECT says not active, but streamActive is not false ??"));+            result = paUnanticipatedHostError;+            PaWinWDM_SetLastErrorInfo(result, "StopStream: GECT says not active, but streamActive = %d", stream->streamActive);+        }+    }+    else+    {+        if (stream->threadResult != paNoError)+        {+            PA_DEBUG(("StopStream: Stream not active (%d)\n", stream->threadResult));+            result = stream->threadResult;+            stream->threadResult = paNoError;+        }+    }++    if (stream->streamThread != NULL)+    {+        CloseHandle(stream->streamThread);+        stream->streamThread = 0;+    }+    stream->streamStarted = 0;+    stream->streamActive = 0;++    if(doCb)+    {+        /* Do user callback now after all state has been reset */+        /* This means it should be safe for the called function */+        /* to invoke e.g. StartStream */+        if( stream->streamRepresentation.streamFinishedCallback != 0 )+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );+    }++    PA_LOGL_;+    return result;+}++static PaError AbortStream( PaStream *s )+{+    PaError result = paNoError;+    PaWinWdmStream *stream = (PaWinWdmStream*)s;+    int doCb = 0;++    PA_LOGE_;++    if(stream->streamActive)+    {+        doCb = 1;+        stream->streamAbort = 1;+        SetEvent(stream->eventAbort); /* Signal immediately */+        if (WaitForSingleObject(stream->streamThread, 10000) != WAIT_OBJECT_0)+        {+            TerminateThread(stream->streamThread, -1);+            result = paTimedOut;++            PA_DEBUG(("AbortStream: stream thread terminated\n"));+        }+        assert(!stream->streamActive);+    }+    CloseHandle(stream->streamThread);+    stream->streamThread = NULL;+    stream->streamStarted = 0;++    if(doCb)+    {+        /* Do user callback now after all state has been reset */+        /* This means it should be safe for the called function */+        /* to invoke e.g. StartStream */+        if( stream->streamRepresentation.streamFinishedCallback != 0 )+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );+    }++    stream->streamActive = 0;+    stream->streamStarted = 0;++    PA_LOGL_;+    return result;+}+++static PaError IsStreamStopped( PaStream *s )+{+    PaWinWdmStream *stream = (PaWinWdmStream*)s;+    int result = 0;++    PA_LOGE_;++    if(!stream->streamStarted)+        result = 1;++    PA_LOGL_;+    return result;+}+++static PaError IsStreamActive( PaStream *s )+{+    PaWinWdmStream *stream = (PaWinWdmStream*)s;+    int result = 0;++    PA_LOGE_;++    if(stream->streamActive)+        result = 1;++    PA_LOGL_;+    return result;+}+++static PaTime GetStreamTime( PaStream* s )+{+    PA_LOGE_;+    PA_LOGL_;+    (void)s;+    return PaUtil_GetTime();+}+++static double GetStreamCpuLoad( PaStream* s )+{+    PaWinWdmStream *stream = (PaWinWdmStream*)s;+    double result;+    PA_LOGE_;+    result = PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );+    PA_LOGL_;+    return result;+}+++/*+As separate stream interfaces are used for blocking and callback+streams, the following functions can be guaranteed to only be called+for blocking streams.+*/++static PaError ReadStream( PaStream* s,+                          void *buffer,+                          unsigned long frames )+{+    PaWinWdmStream *stream = (PaWinWdmStream*)s;++    PA_LOGE_;++    /* suppress unused variable warnings */+    (void) buffer;+    (void) frames;+    (void) stream;++    /* IMPLEMENT ME, see portaudio.h for required behavior*/+    PA_LOGL_;+    return paInternalError;+}+++static PaError WriteStream( PaStream* s,+                           const void *buffer,+                           unsigned long frames )+{+    PaWinWdmStream *stream = (PaWinWdmStream*)s;++    PA_LOGE_;++    /* suppress unused variable warnings */+    (void) buffer;+    (void) frames;+    (void) stream;++    /* IMPLEMENT ME, see portaudio.h for required behavior*/+    PA_LOGL_;+    return paInternalError;+}+++static signed long GetStreamReadAvailable( PaStream* s )+{+    PaWinWdmStream *stream = (PaWinWdmStream*)s;++    PA_LOGE_;++    /* suppress unused variable warnings */+    (void) stream;++    /* IMPLEMENT ME, see portaudio.h for required behavior*/+    PA_LOGL_;+    return 0;+}+++static signed long GetStreamWriteAvailable( PaStream* s )+{+    PaWinWdmStream *stream = (PaWinWdmStream*)s;++    PA_LOGE_;+    /* suppress unused variable warnings */+    (void) stream;++    /* IMPLEMENT ME, see portaudio.h for required behavior*/+    PA_LOGL_;+    return 0;+}++/***************************************************************************************/+/* Event and submit handlers for WaveCyclic                                            */+/***************************************************************************************/++static PaError PaPinCaptureEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    PaError result = paNoError;+    ring_buffer_size_t frameCount;+    DATAPACKET* packet = pInfo->stream->capture.packets + eventIndex;++    assert( eventIndex < pInfo->stream->capture.noOfPackets );++    if (packet->Header.DataUsed == 0)+    {+        PA_HP_TRACE((pInfo->stream->hLog, ">>> Capture bogus event (no data): idx=%u", eventIndex));++        /* Bogus event, reset! This is to handle the behavior of this USB mic: http://shop.xtz.se/measurement-system/microphone-to-dirac-live-room-correction-suite +           on startup of streaming, where it erroneously sets the event without the corresponding buffer being filled (DataUsed == 0) */+        ResetEvent(packet->Signal.hEvent);++        result = -1;    /* Only need this to be NOT paNoError */+    }+    else+    {+        pInfo->capturePackets[pInfo->captureHead & cPacketsArrayMask].packet = packet;++        frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer, packet->Header.Data, pInfo->stream->capture.framesPerBuffer);++        PA_HP_TRACE((pInfo->stream->hLog, ">>> Capture event: idx=%u (frames=%u)", eventIndex, frameCount));+        ++pInfo->captureHead;+    }++    --pInfo->pending; /* This needs to be done in either case */+    return result;+}++static PaError PaPinCaptureSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    PaError result = paNoError;+    DATAPACKET* packet = pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet;+    pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;+    assert(packet != 0);+    PA_HP_TRACE((pInfo->stream->hLog, "Capture submit: %u", eventIndex));+    packet->Header.DataUsed = 0; /* Reset for reuse */+    ResetEvent(packet->Signal.hEvent);+    result = PinRead(pInfo->stream->capture.pPin->handle, packet);+    ++pInfo->pending;+    return result;+}++static PaError PaPinRenderEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    assert( eventIndex < pInfo->stream->render.noOfPackets );++    pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask].packet = pInfo->stream->render.packets + eventIndex;+    PA_HP_TRACE((pInfo->stream->hLog, "<<< Render event : idx=%u head=%u", eventIndex, pInfo->renderHead));+    ++pInfo->renderHead;+    --pInfo->pending;+    return paNoError;+}++static PaError PaPinRenderSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    PaError result = paNoError;+    DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;+    pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;+    assert(packet != 0);++    PA_HP_TRACE((pInfo->stream->hLog, "Render submit : %u idx=%u", pInfo->renderTail, (unsigned)(packet - pInfo->stream->render.packets)));+    ResetEvent(packet->Signal.hEvent);+    result = PinWrite(pInfo->stream->render.pPin->handle, packet);+    /* Reset event, just in case we have an analogous situation to capture (see PaPinCaptureSubmitHandler_WaveCyclic) */+    ++pInfo->pending;+    if (pInfo->priming)+    {+        --pInfo->priming;+    }+    return result;+}++/***************************************************************************************/+/* Event and submit handlers for WaveRT                                                */+/***************************************************************************************/++static PaError PaPinCaptureEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    unsigned long pos;+    unsigned realInBuf;+    unsigned frameCount;+    PaWinWdmIOInfo* pCapture = &pInfo->stream->capture;+    const unsigned halfInputBuffer = pCapture->hostBufferSize >> 1;+    PaWinWdmPin* pin = pCapture->pPin;+    DATAPACKET* packet = 0;++    /* Get hold of current ADC position */+    pin->fnAudioPosition(pin, &pos);+    /* Wrap it (robi: why not use hw latency compensation here ?? because pos then gets _way_ off from+    where it should be, i.e. at beginning or half buffer position. Why? No idea.)  */++    pos %= pCapture->hostBufferSize;+    /* Then realInBuf will point to "other" half of double buffer */+    realInBuf = pos < halfInputBuffer ? 1U : 0U;++    packet = pInfo->stream->capture.packets + realInBuf;++    /* Call barrier (or dummy) */+    pin->fnMemBarrier();++    /* Put it in queue */+    frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer, packet->Header.Data, pCapture->framesPerBuffer);++    pInfo->capturePackets[pInfo->captureHead & cPacketsArrayMask].packet = packet;++    PA_HP_TRACE((pInfo->stream->hLog, "Capture event (WaveRT): idx=%u head=%u (pos = %4.1lf%%, frames=%u)", realInBuf, pInfo->captureHead, (pos * 100.0 / pCapture->hostBufferSize), frameCount));++    ++pInfo->captureHead;+    --pInfo->pending;++    return paNoError;+}++static PaError PaPinCaptureEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    unsigned long pos;+    unsigned bytesToRead;+    PaWinWdmIOInfo* pCapture = &pInfo->stream->capture;+    const unsigned halfInputBuffer = pCapture->hostBufferSize>>1;+    PaWinWdmPin* pin = pInfo->stream->capture.pPin;++    /* Get hold of current ADC position */+    pin->fnAudioPosition(pin, &pos);+    /* Wrap it (robi: why not use hw latency compensation here ?? because pos then gets _way_ off from+    where it should be, i.e. at beginning or half buffer position. Why? No idea.)  */+    /* Compensate for HW FIFO to get to last read buffer position */+    pos += pin->hwLatency;+    pos %= pCapture->hostBufferSize;+    /* Need to align position on frame boundary */+    pos &= ~(pCapture->bytesPerFrame - 1);++    /* Call barrier (or dummy) */+    pin->fnMemBarrier();++    /* Put it in "queue" */+    bytesToRead = (pCapture->hostBufferSize + pos - pCapture->lastPosition) % pCapture->hostBufferSize;+    if (bytesToRead > 0)+    {+        unsigned frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer,+            pCapture->hostBuffer + pCapture->lastPosition,+            bytesToRead / pCapture->bytesPerFrame);++        pCapture->lastPosition = (pCapture->lastPosition + frameCount * pCapture->bytesPerFrame) % pCapture->hostBufferSize;++        PA_HP_TRACE((pInfo->stream->hLog, "Capture event (WaveRTPolled): pos = %4.1lf%%, framesRead=%u", (pos * 100.0 / pCapture->hostBufferSize), frameCount));+        ++pInfo->captureHead;+        --pInfo->pending;+    }+    return paNoError;+}++static PaError PaPinCaptureSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;+    ++pInfo->pending;+    return paNoError;+}++static PaError PaPinCaptureSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;+    ++pInfo->pending;+    return paNoError;+}++static PaError PaPinRenderEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    unsigned long pos;+    unsigned realOutBuf;+    PaWinWdmIOInfo* pRender = &pInfo->stream->render;+    const unsigned halfOutputBuffer = pRender->hostBufferSize >> 1;+    PaWinWdmPin* pin = pInfo->stream->render.pPin;+    PaIOPacket* ioPacket = &pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask];++    /* Get hold of current DAC position */+    pin->fnAudioPosition(pin, &pos);+    /* Compensate for HW FIFO to get to last read buffer position */+    pos += pin->hwLatency;+    /* Wrap it */+    pos %= pRender->hostBufferSize;+    /* And align it, not sure its really needed though */+    pos &= ~(pRender->bytesPerFrame - 1);+    /* Then realOutBuf will point to "other" half of double buffer */+    realOutBuf = pos < halfOutputBuffer ? 1U : 0U;++    if (pInfo->priming)+    {+        realOutBuf = pInfo->renderHead & 0x1;+    }+    ioPacket->packet = pInfo->stream->render.packets + realOutBuf;+    ioPacket->startByte = realOutBuf * halfOutputBuffer;+    ioPacket->lengthBytes = halfOutputBuffer;++    PA_HP_TRACE((pInfo->stream->hLog, "Render event (WaveRT) : idx=%u head=%u (pos = %4.1lf%%)", realOutBuf, pInfo->renderHead, (pos * 100.0 / pRender->hostBufferSize) ));++    ++pInfo->renderHead;+    --pInfo->pending;+    return paNoError;+}++static PaError PaPinRenderEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    unsigned long pos;+    unsigned realOutBuf;+    unsigned bytesToWrite;++    PaWinWdmIOInfo* pRender = &pInfo->stream->render;+    const unsigned halfOutputBuffer = pRender->hostBufferSize >> 1;+    PaWinWdmPin* pin = pInfo->stream->render.pPin;+    PaIOPacket* ioPacket = &pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask];++    /* Get hold of current DAC position */+    pin->fnAudioPosition(pin, &pos);+    /* Compensate for HW FIFO to get to last read buffer position */+    pos += pin->hwLatency;+    /* Wrap it */+    pos %= pRender->hostBufferSize;+    /* And align it, not sure its really needed though */+    pos &= ~(pRender->bytesPerFrame - 1);++    if (pInfo->priming)+    {+        realOutBuf = pInfo->renderHead & 0x1;+        ioPacket->packet = pInfo->stream->render.packets + realOutBuf;+        ioPacket->startByte = realOutBuf * halfOutputBuffer;+        ioPacket->lengthBytes = halfOutputBuffer;+        ++pInfo->renderHead;+        --pInfo->pending;+    }+    else+    {+        bytesToWrite = (pRender->hostBufferSize + pos - pRender->lastPosition) % pRender->hostBufferSize;+        ++pRender->pollCntr;+        if (bytesToWrite >= halfOutputBuffer)+        {+            realOutBuf = (pos < halfOutputBuffer) ? 1U : 0U;+            ioPacket->packet = pInfo->stream->render.packets + realOutBuf;+            pRender->lastPosition = realOutBuf ? 0U : halfOutputBuffer;+            ioPacket->startByte = realOutBuf * halfOutputBuffer;+            ioPacket->lengthBytes = halfOutputBuffer;+            ++pInfo->renderHead;+            --pInfo->pending;+            PA_HP_TRACE((pInfo->stream->hLog, "Render event (WaveRTPolled) : idx=%u head=%u (pos = %4.1lf%%, cnt=%u)", realOutBuf, pInfo->renderHead, (pos * 100.0 / pRender->hostBufferSize), pRender->pollCntr));+            pRender->pollCntr = 0;+        }+    }+    return paNoError;+}++static PaError PaPinRenderSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    PaWinWdmPin* pin = pInfo->stream->render.pPin;+    pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;+    /* Call barrier (if needed) */+    pin->fnMemBarrier();+    PA_HP_TRACE((pInfo->stream->hLog, "Render submit (WaveRT) : submit=%u", pInfo->renderTail));+    ++pInfo->pending;+    if (pInfo->priming)+    {+        --pInfo->priming;+        if (pInfo->priming)+        {+            PA_HP_TRACE((pInfo->stream->hLog, "Setting WaveRT event for priming (2)"));+            SetEvent(pInfo->stream->render.events[0]);+        }+    }+    return paNoError;+}++static PaError PaPinRenderSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)+{+    PaWinWdmPin* pin = pInfo->stream->render.pPin;+    pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;+    /* Call barrier (if needed) */+    pin->fnMemBarrier();+    PA_HP_TRACE((pInfo->stream->hLog, "Render submit (WaveRTPolled) : submit=%u", pInfo->renderTail));+    ++pInfo->pending;+    if (pInfo->priming)+    {+        --pInfo->priming;+        if (pInfo->priming)+        {+            PA_HP_TRACE((pInfo->stream->hLog, "Setting WaveRT event for priming (2)"));+            SetEvent(pInfo->stream->render.events[0]);+        }+    }+    return paNoError;+}
+ portaudio/src/hostapi/wmme/pa_win_wmme.c view
@@ -0,0 +1,4011 @@+/*+ * $Id: pa_win_wmme.c 1874 2012-10-31 06:20:59Z rbencina $+ * pa_win_wmme.c+ * Implementation of PortAudio for Windows MultiMedia Extensions (WMME)       + *                                                                                         + * PortAudio Portable Real-Time Audio Library+ * Latest Version at: http://www.portaudio.com+ *+ * Authors: Ross Bencina and Phil Burk+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/* Modification History:+ PLB = Phil Burk+ JM = Julien Maillard+ RDB = Ross Bencina+ PLB20010402 - sDevicePtrs now allocates based on sizeof(pointer)+ PLB20010413 - check for excessive numbers of channels+ PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC+               including conditional inclusion of memory.h,+               and explicit typecasting on memory allocation+ PLB20010802 - use GlobalAlloc for sDevicesPtr instead of PaHost_AllocFastMemory+ PLB20010816 - pass process instead of thread to SetPriorityClass()+ PLB20010927 - use number of frames instead of real-time for CPULoad calculation.+ JM20020118 - prevent hung thread when buffers underflow.+ PLB20020321 - detect Win XP versus NT, 9x; fix DBUG typo; removed init of CurrentCount+ RDB20020411 - various renaming cleanups, factored streamData alloc and cpu usage init+ RDB20020417 - stopped counting WAVE_MAPPER when there were no real devices+               refactoring, renaming and fixed a few edge case bugs+ RDB20020531 - converted to V19 framework+ ** NOTE  maintanance history is now stored in CVS **+*/++/** @file+	@ingroup hostapi_src++    @brief Win32 host API implementation for the Windows MultiMedia Extensions (WMME) audio API.+*/++/*+    How it works:++    For both callback and blocking read/write streams we open the MME devices+    in CALLBACK_EVENT mode. In this mode, MME signals an Event object whenever+    it has finished with a buffer (either filled it for input, or played it+    for output). Where necessary, we block waiting for Event objects using+    WaitMultipleObjects().++    When implementing a PA callback stream, we set up a high priority thread+    which waits on the MME buffer Events and drains/fills the buffers when+    they are ready.++    When implementing a PA blocking read/write stream, we simply wait on these+    Events (when necessary) inside the ReadStream() and WriteStream() functions.+*/++#include <stdio.h>+#include <stdlib.h>+#include <math.h>+#include <windows.h>+#include <mmsystem.h>+#ifndef UNDER_CE+#include <process.h>+#endif+#include <assert.h>+/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */+#ifndef __MWERKS__+#include <malloc.h>+#include <memory.h>+#endif /* __MWERKS__ */++#include "portaudio.h"+#include "pa_trace.h"+#include "pa_util.h"+#include "pa_allocation.h"+#include "pa_hostapi.h"+#include "pa_stream.h"+#include "pa_cpuload.h"+#include "pa_process.h"+#include "pa_debugprint.h"++#include "pa_win_wmme.h"+#include "pa_win_waveformat.h"++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+#include "pa_win_wdmks_utils.h"+#ifndef DRV_QUERYDEVICEINTERFACE+#define DRV_QUERYDEVICEINTERFACE     (DRV_RESERVED + 12)+#endif+#ifndef DRV_QUERYDEVICEINTERFACESIZE+#define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)+#endif+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */++/* use CreateThread for CYGWIN, _beginthreadex for all others */+#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)+#define CREATE_THREAD (HANDLE)_beginthreadex( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )+#define PA_THREAD_FUNC static unsigned WINAPI+#define PA_THREAD_ID unsigned+#else+#define CREATE_THREAD CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )+#define PA_THREAD_FUNC static DWORD WINAPI+#define PA_THREAD_ID DWORD+#endif+#if (defined(_WIN32_WCE))+#pragma comment(lib, "Coredll.lib")+#elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */+#pragma comment(lib, "winmm.lib")+#endif++/*+ provided in newer platform sdks+ */+#ifndef DWORD_PTR+    #if defined(_WIN64)+        #define DWORD_PTR unsigned __int64+    #else+        #define DWORD_PTR unsigned long+    #endif+#endif++/************************************************* Constants ********/++#define PA_MME_USE_HIGH_DEFAULT_LATENCY_    (0)  /* For debugging glitches. */++#if PA_MME_USE_HIGH_DEFAULT_LATENCY_+ #define PA_MME_WIN_9X_DEFAULT_LATENCY_                             (0.4)+ #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_                       (4)+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_	        (4)+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_	        (4)+ #define PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_	(16)+ #define PA_MME_MAX_HOST_BUFFER_SECS_				                (0.3)       /* Do not exceed unless user buffer exceeds */+ #define PA_MME_MAX_HOST_BUFFER_BYTES_				                (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */+#else+ #define PA_MME_WIN_9X_DEFAULT_LATENCY_                             (0.2)+ #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_                       (2)+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_	        (3)         /* always use at least 3 input buffers for full duplex */+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_	        (2)+ #define PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_	(16)+ #define PA_MME_MAX_HOST_BUFFER_SECS_				                (0.1)       /* Do not exceed unless user buffer exceeds */+ #define PA_MME_MAX_HOST_BUFFER_BYTES_				                (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */+#endif++/* Use higher latency for NT because it is even worse at real-time+   operation than Win9x.+*/+#define PA_MME_WIN_NT_DEFAULT_LATENCY_                              (0.4)++/* Default low latency for WDM based systems. This is based on a rough+   survey of workable latency settings using patest_wmme_find_best_latency_params.c.+   See pdf attached to ticket 185 for a graph of the survey results:+   http://www.portaudio.com/trac/ticket/185+   +   Workable latencies varied between 40ms and ~80ms on different systems (different+   combinations of hardware, 32 and 64 bit, WinXP, Vista and Win7. We didn't+   get enough Vista results to know if Vista has systemically worse latency.+   For now we choose a safe value across all Windows versions here.+*/+#define PA_MME_WIN_WDM_DEFAULT_LATENCY_                             (0.090)+++/* When client suggestedLatency could result in many host buffers, we aim to have around 8, +   based off Windows documentation that suggests that the kmixer uses 8 buffers. This choice+   is somewhat arbitrary here, since we havn't observed significant stability degredation +   with using either more, or less buffers.     +*/+#define PA_MME_TARGET_HOST_BUFFER_COUNT_    8++#define PA_MME_MIN_TIMEOUT_MSEC_        (1000)++static const char constInputMapperSuffix_[] = " - Input";+static const char constOutputMapperSuffix_[] = " - Output";++/*+copies TCHAR string to explicit char string+*/+char *StrTCpyToC(char *to, const TCHAR *from)+{+#if !defined(_UNICODE) && !defined(UNICODE)+	return strcpy(to, from);+#else+	int count = wcslen(from);+	if (count != 0)+		if (WideCharToMultiByte(CP_ACP, 0, from, count, to, count, NULL, NULL) == 0)+			return NULL;+	return to;+#endif+}++/*+returns length of TCHAR string+*/+size_t StrTLen(const TCHAR *str)+{+#if !defined(_UNICODE) && !defined(UNICODE)+	return strlen(str);+#else+	return wcslen(str);	+#endif+}++/********************************************************************/++typedef struct PaWinMmeStream PaWinMmeStream;     /* forward declaration */++/* prototypes for functions declared in this file */++#ifdef __cplusplus+extern "C"+{+#endif /* __cplusplus */++PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );++#ifdef __cplusplus+}+#endif /* __cplusplus */++static void Terminate( struct PaUtilHostApiRepresentation *hostApi );+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,+                           PaStream** stream,+                           const PaStreamParameters *inputParameters,+                           const PaStreamParameters *outputParameters,+                           double sampleRate,+                           unsigned long framesPerBuffer,+                           PaStreamFlags streamFlags,+                           PaStreamCallback *streamCallback,+                           void *userData );+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,+                                  const PaStreamParameters *inputParameters,+                                  const PaStreamParameters *outputParameters,+                                  double sampleRate );+static PaError CloseStream( PaStream* stream );+static PaError StartStream( PaStream *stream );+static PaError StopStream( PaStream *stream );+static PaError AbortStream( PaStream *stream );+static PaError IsStreamStopped( PaStream *s );+static PaError IsStreamActive( PaStream *stream );+static PaTime GetStreamTime( PaStream *stream );+static double GetStreamCpuLoad( PaStream* stream );+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );+static signed long GetStreamReadAvailable( PaStream* stream );+static signed long GetStreamWriteAvailable( PaStream* stream );+++/* macros for setting last host error information */++#ifdef UNICODE++#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \+    {                                                                   \+        wchar_t mmeErrorTextWide[ MAXERRORLENGTH ];                     \+        char mmeErrorText[ MAXERRORLENGTH ];                            \+        waveInGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH );   \+        WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\+            mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL );  \+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \+    }++#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \+    {                                                                   \+        wchar_t mmeErrorTextWide[ MAXERRORLENGTH ];                     \+        char mmeErrorText[ MAXERRORLENGTH ];                            \+        waveOutGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH );  \+        WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\+            mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL );  \+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \+    }+    +#else /* !UNICODE */++#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \+    {                                                                   \+        char mmeErrorText[ MAXERRORLENGTH ];                            \+        waveInGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH );   \+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \+    }++#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \+    {                                                                   \+        char mmeErrorText[ MAXERRORLENGTH ];                            \+        waveOutGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH );  \+        PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText );   \+    }++#endif /* UNICODE */+++static void PaMme_SetLastSystemError( DWORD errorCode )+{+    char *lpMsgBuf;+    FormatMessage(+        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,+        NULL,+        errorCode,+        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),+        (LPTSTR) &lpMsgBuf,+        0,+        NULL+    );+    PaUtil_SetLastHostErrorInfo( paMME, errorCode, lpMsgBuf );+    LocalFree( lpMsgBuf );+}++#define PA_MME_SET_LAST_SYSTEM_ERROR( errorCode ) \+    PaMme_SetLastSystemError( errorCode )+++/* PaError returning wrappers for some commonly used win32 functions+    note that we allow passing a null ptr to have no effect.+*/++static PaError CreateEventWithPaError( HANDLE *handle,+        LPSECURITY_ATTRIBUTES lpEventAttributes,+        BOOL bManualReset,+        BOOL bInitialState,+        LPCTSTR lpName )+{+    PaError result = paNoError;++    *handle = NULL;+    +    *handle = CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName );+    if( *handle == NULL )+    {+        result = paUnanticipatedHostError;+        PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );+    }++    return result;+}+++static PaError ResetEventWithPaError( HANDLE handle )+{+    PaError result = paNoError;++    if( handle )+    {+        if( ResetEvent( handle ) == 0 )+        {+            result = paUnanticipatedHostError;+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );+        }+    }++    return result;+}+++static PaError CloseHandleWithPaError( HANDLE handle )+{+    PaError result = paNoError;+    +    if( handle )+    {+        if( CloseHandle( handle ) == 0 )+        {+            result = paUnanticipatedHostError;+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );+        }+    }+    +    return result;+}+++/* PaWinMmeHostApiRepresentation - host api datastructure specific to this implementation */++typedef struct+{+    PaUtilHostApiRepresentation inheritedHostApiRep;+    PaUtilStreamInterface callbackStreamInterface;+    PaUtilStreamInterface blockingStreamInterface;++    PaUtilAllocationGroup *allocations;+    +    int inputDeviceCount, outputDeviceCount;++    /** winMmeDeviceIds is an array of WinMme device ids.+        fields in the range [0, inputDeviceCount) are input device ids,+        and [inputDeviceCount, inputDeviceCount + outputDeviceCount) are output+        device ids.+     */ +    UINT *winMmeDeviceIds;+}+PaWinMmeHostApiRepresentation;+++typedef struct+{+    PaDeviceInfo inheritedDeviceInfo;+    DWORD dwFormats; /**<< standard formats bitmask from the WAVEINCAPS and WAVEOUTCAPS structures */+    char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/+    char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/+}+PaWinMmeDeviceInfo;+++/*************************************************************************+ * Returns recommended device ID.+ * On the PC, the recommended device can be specified by the user by+ * setting an environment variable. For example, to use device #1.+ *+ *    set PA_RECOMMENDED_OUTPUT_DEVICE=1+ *+ * The user should first determine the available device ID by using+ * the supplied application "pa_devs".+ */+#define PA_ENV_BUF_SIZE_  (32)+#define PA_REC_IN_DEV_ENV_NAME_  ("PA_RECOMMENDED_INPUT_DEVICE")+#define PA_REC_OUT_DEV_ENV_NAME_  ("PA_RECOMMENDED_OUTPUT_DEVICE")+static PaDeviceIndex GetEnvDefaultDeviceID( char *envName )+{+    PaDeviceIndex recommendedIndex = paNoDevice;+    DWORD   hresult;+    char    envbuf[PA_ENV_BUF_SIZE_];++#ifndef WIN32_PLATFORM_PSPC /* no GetEnvironmentVariable on PocketPC */++    /* Let user determine default device by setting environment variable. */+    hresult = GetEnvironmentVariableA( envName, envbuf, PA_ENV_BUF_SIZE_ );+    if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE_) )+    {+        recommendedIndex = atoi( envbuf );+    }+#endif++    return recommendedIndex;+}+++static void InitializeDefaultDeviceIdsFromEnv( PaWinMmeHostApiRepresentation *hostApi )+{+    PaDeviceIndex device;++    /* input */+    device = GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME_ );+    if( device != paNoDevice &&+            ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&+            hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxInputChannels > 0 )+    {+        hostApi->inheritedHostApiRep.info.defaultInputDevice = device;+    }++    /* output */+    device = GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME_ );+    if( device != paNoDevice &&+            ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&+            hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxOutputChannels > 0 )+    {+        hostApi->inheritedHostApiRep.info.defaultOutputDevice = device;+    }+}+++/** Convert external PA ID to a windows multimedia device ID+*/+static UINT LocalDeviceIndexToWinMmeDeviceId( PaWinMmeHostApiRepresentation *hostApi, PaDeviceIndex device )+{+    assert( device >= 0 && device < hostApi->inputDeviceCount + hostApi->outputDeviceCount );++	return hostApi->winMmeDeviceIds[ device ];+}+++static int SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( PaSampleFormat sampleFormat, unsigned long winMmeSpecificFlags )+{+    int waveFormatTag = 0;++    if( winMmeSpecificFlags & paWinMmeWaveFormatDolbyAc3Spdif )+        waveFormatTag = PAWIN_WAVE_FORMAT_DOLBY_AC3_SPDIF;+    else if( winMmeSpecificFlags & paWinMmeWaveFormatWmaSpdif )+        waveFormatTag = PAWIN_WAVE_FORMAT_WMA_SPDIF;+    else+        waveFormatTag = PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat );++    return waveFormatTag;+}+++static PaError QueryInputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )+{+    MMRESULT mmresult;+    +    switch( mmresult = waveInOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )+    {+        case MMSYSERR_NOERROR:+            return paNoError;+        case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */+            return paDeviceUnavailable;+        case MMSYSERR_NODRIVER:	    /* No device driver is present. */+            return paDeviceUnavailable;+        case MMSYSERR_NOMEM:	    /* Unable to allocate or lock memory. */+            return paInsufficientMemory;+        case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */+            return paSampleFormatNotSupported;+                    +        case MMSYSERR_BADDEVICEID:	/* Specified device identifier is out of range. */+            /* falls through */+        default:+            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+            return paUnanticipatedHostError;+    }+}+++static PaError QueryOutputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )+{+    MMRESULT mmresult;+    +    switch( mmresult = waveOutOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )+    {+        case MMSYSERR_NOERROR:+            return paNoError;+        case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */+            return paDeviceUnavailable;+        case MMSYSERR_NODRIVER:	    /* No device driver is present. */+            return paDeviceUnavailable;+        case MMSYSERR_NOMEM:	    /* Unable to allocate or lock memory. */+            return paInsufficientMemory;+        case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */+            return paSampleFormatNotSupported;+                    +        case MMSYSERR_BADDEVICEID:	/* Specified device identifier is out of range. */+            /* falls through */+        default:+            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+            return paUnanticipatedHostError;+    }+}+++static PaError QueryFormatSupported( PaDeviceInfo *deviceInfo,+        PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*),+        int winMmeDeviceId, int channels, double sampleRate, unsigned long winMmeSpecificFlags )+{+    PaWinMmeDeviceInfo *winMmeDeviceInfo = (PaWinMmeDeviceInfo*)deviceInfo;+    PaWinWaveFormat waveFormat;+    PaSampleFormat sampleFormat;+    int waveFormatTag;+    +    /* @todo at the moment we only query with 16 bit sample format and directout speaker config*/++    sampleFormat = paInt16;+    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );++    if( waveFormatTag == PaWin_SampleFormatToLinearWaveFormatTag( paInt16 ) ){+    +        /* attempt bypass querying the device for linear formats */++        if( sampleRate == 11025.0+            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16))+                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){++            return paNoError;+        }++        if( sampleRate == 22050.0+            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16))+                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){++            return paNoError;+        }++        if( sampleRate == 44100.0+            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16))+                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){++            return paNoError;+        }+    }+++    /* first, attempt to query the device using WAVEFORMATEXTENSIBLE, +       if this fails we fall back to WAVEFORMATEX */++    PaWin_InitializeWaveFormatExtensible( &waveFormat, channels, sampleFormat, waveFormatTag,+            sampleRate, PAWIN_SPEAKER_DIRECTOUT );++    if( waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat ) == paNoError )+        return paNoError;++    PaWin_InitializeWaveFormatEx( &waveFormat, channels, sampleFormat, waveFormatTag, sampleRate );++    return waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat );+}+++#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_  (13) /* must match array length below */+static double defaultSampleRateSearchOrder_[] =+    { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,+        16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };++static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int winMmeDeviceId,+        PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*), int maxChannels )+{+    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;+    int i;+    +    deviceInfo->defaultSampleRate = 0.;++    for( i=0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )+    {+        double sampleRate = defaultSampleRateSearchOrder_[ i ]; +        PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate, 0 );+        if( paerror == paNoError )+        {+            deviceInfo->defaultSampleRate = sampleRate;+            break;+        }+    }+}+++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+static int QueryWaveInKSFilterMaxChannels( int waveInDeviceId, int *maxChannels )+{+    void *devicePath;+    DWORD devicePathSize;+    int result = 0;++    if( waveInMessage((HWAVEIN)waveInDeviceId, DRV_QUERYDEVICEINTERFACESIZE,+            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )+        return 0;++    devicePath = PaUtil_AllocateMemory( devicePathSize );+    if( !devicePath )+        return 0;++    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */+    if( waveInMessage((HWAVEIN)waveInDeviceId, DRV_QUERYDEVICEINTERFACE,+            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )+    {+        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 1  );+        if( count > 0 )+        {+            *maxChannels = count;+            result = 1;+        }+    }++    PaUtil_FreeMemory( devicePath );++    return result;+}+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */+++static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,+        PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeInputDeviceId, int *success )+{+    PaError result = paNoError;+    char *deviceName; /* non-const ptr */+    MMRESULT mmresult;+    WAVEINCAPS wic;+    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;+    +    *success = 0;++    mmresult = waveInGetDevCaps( winMmeInputDeviceId, &wic, sizeof( WAVEINCAPS ) );+    if( mmresult == MMSYSERR_NOMEM )+    {+        result = paInsufficientMemory;+        goto error;+    }+    else if( mmresult != MMSYSERR_NOERROR )+    {+        /* instead of returning paUnanticipatedHostError we return+            paNoError, but leave success set as 0. This allows+            Pa_Initialize to just ignore this device, without failing+            the entire initialisation process.+        */+        return paNoError;+    }           ++    if( winMmeInputDeviceId == WAVE_MAPPER )+    {+        /* Append I/O suffix to WAVE_MAPPER device. */+        deviceName = (char *)PaUtil_GroupAllocateMemory(+                    winMmeHostApi->allocations,+					(long) (StrTLen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_)) );+        if( !deviceName )+        {+            result = paInsufficientMemory;+            goto error;+        }+        StrTCpyToC( deviceName, wic.szPname );+        strcat( deviceName, constInputMapperSuffix_ );+    }+    else+    {+        deviceName = (char*)PaUtil_GroupAllocateMemory(+                    winMmeHostApi->allocations, +					(long) (StrTLen( wic.szPname ) + 1) );+        if( !deviceName )+        {+            result = paInsufficientMemory;+            goto error;+        }+        StrTCpyToC( deviceName, wic.szPname  );+    }+    deviceInfo->name = deviceName;++    if( wic.wChannels == 0xFFFF || wic.wChannels < 1 || wic.wChannels > 255 ){+        /* For Windows versions using WDM (possibly Windows 98 ME and later)+         * the kernel mixer sits between the application and the driver. As a result,+         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.+         * When this happens we assume the device is stereo and set a flag+         * so that other channel counts can be tried with OpenStream -- i.e. when+         * device*ChannelCountIsKnown is false, OpenStream will try whatever+         * channel count you supply.+         * see also InitializeOutputDeviceInfo() below.+     */++        PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", wic.wChannels ));+        deviceInfo->maxInputChannels = 2;+        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 0;+    }else{+        deviceInfo->maxInputChannels = wic.wChannels;+        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 1;+    }++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+    winMmeDeviceInfo->deviceInputChannelCountIsKnown = +            QueryWaveInKSFilterMaxChannels( winMmeInputDeviceId, &deviceInfo->maxInputChannels );+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */++    winMmeDeviceInfo->dwFormats = wic.dwFormats;++    DetectDefaultSampleRate( winMmeDeviceInfo, winMmeInputDeviceId,+            QueryInputWaveFormatEx, deviceInfo->maxInputChannels );++    *success = 1;+    +error:+    return result;+}+++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+static int QueryWaveOutKSFilterMaxChannels( int waveOutDeviceId, int *maxChannels )+{+    void *devicePath;+    DWORD devicePathSize;+    int result = 0;++    if( waveOutMessage((HWAVEOUT)waveOutDeviceId, DRV_QUERYDEVICEINTERFACESIZE,+            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )+        return 0;++    devicePath = PaUtil_AllocateMemory( devicePathSize );+    if( !devicePath )+        return 0;++    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */+    if( waveOutMessage((HWAVEOUT)waveOutDeviceId, DRV_QUERYDEVICEINTERFACE,+            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )+    {+        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 0  );+        if( count > 0 )+        {+            *maxChannels = count;+            result = 1;+        }+    }++    PaUtil_FreeMemory( devicePath );++    return result;+}+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */+++static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,+        PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeOutputDeviceId, int *success )+{+    PaError result = paNoError;+    char *deviceName; /* non-const ptr */+    MMRESULT mmresult;+    WAVEOUTCAPS woc;+    PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;+#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+    int wdmksDeviceOutputChannelCountIsKnown;+#endif++    *success = 0;++    mmresult = waveOutGetDevCaps( winMmeOutputDeviceId, &woc, sizeof( WAVEOUTCAPS ) );+    if( mmresult == MMSYSERR_NOMEM )+    {+        result = paInsufficientMemory;+        goto error;+    }+    else if( mmresult != MMSYSERR_NOERROR )+    {+        /* instead of returning paUnanticipatedHostError we return+            paNoError, but leave success set as 0. This allows+            Pa_Initialize to just ignore this device, without failing+            the entire initialisation process.+        */+        return paNoError;+    }++    if( winMmeOutputDeviceId == WAVE_MAPPER )+    {+        /* Append I/O suffix to WAVE_MAPPER device. */+        deviceName = (char *)PaUtil_GroupAllocateMemory(+                    winMmeHostApi->allocations, +					(long) (StrTLen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_)) );+        if( !deviceName )+        {+            result = paInsufficientMemory;+            goto error;+        }+        StrTCpyToC( deviceName, woc.szPname );+        strcat( deviceName, constOutputMapperSuffix_ );+    }+    else+    {+        deviceName = (char*)PaUtil_GroupAllocateMemory(+                    winMmeHostApi->allocations, +					(long) (StrTLen( woc.szPname ) + 1) );+        if( !deviceName )+        {+            result = paInsufficientMemory;+            goto error;+        }+        StrTCpyToC( deviceName, woc.szPname  );+    }+    deviceInfo->name = deviceName;++    if( woc.wChannels == 0xFFFF || woc.wChannels < 1 || woc.wChannels > 255 ){+        /* For Windows versions using WDM (possibly Windows 98 ME and later)+         * the kernel mixer sits between the application and the driver. As a result,+         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.+         * When this happens we assume the device is stereo and set a flag+         * so that other channel counts can be tried with OpenStream -- i.e. when+         * device*ChannelCountIsKnown is false, OpenStream will try whatever+         * channel count you supply.+         * see also InitializeInputDeviceInfo() above.+     */++        PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", woc.wChannels ));+        deviceInfo->maxOutputChannels = 2;+        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 0;+    }else{+        deviceInfo->maxOutputChannels = woc.wChannels;+        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;+    }++#ifdef PAWIN_USE_WDMKS_DEVICE_INFO+    wdmksDeviceOutputChannelCountIsKnown = QueryWaveOutKSFilterMaxChannels( +			winMmeOutputDeviceId, &deviceInfo->maxOutputChannels );+    if( wdmksDeviceOutputChannelCountIsKnown && !winMmeDeviceInfo->deviceOutputChannelCountIsKnown )+        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;+#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */++    winMmeDeviceInfo->dwFormats = woc.dwFormats;++    DetectDefaultSampleRate( winMmeDeviceInfo, winMmeOutputDeviceId,+            QueryOutputWaveFormatEx, deviceInfo->maxOutputChannels );++    *success = 1;+    +error:+    return result;+}+++static void GetDefaultLatencies( PaTime *defaultLowLatency, PaTime *defaultHighLatency )+{+    OSVERSIONINFO osvi;+    osvi.dwOSVersionInfoSize = sizeof( osvi );+	GetVersionEx( &osvi );++    /* Check for NT */+    if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )+    {+        *defaultLowLatency = PA_MME_WIN_NT_DEFAULT_LATENCY_;+    }+    else if(osvi.dwMajorVersion >= 5)+    {+        *defaultLowLatency  = PA_MME_WIN_WDM_DEFAULT_LATENCY_;+    }+    else+    {+        *defaultLowLatency  = PA_MME_WIN_9X_DEFAULT_LATENCY_;+    }     ++    *defaultHighLatency = *defaultLowLatency * 2;+}+++PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )+{+    PaError result = paNoError;+    int i;+    PaWinMmeHostApiRepresentation *winMmeHostApi;+    int inputDeviceCount, outputDeviceCount, maximumPossibleDeviceCount;+    PaWinMmeDeviceInfo *deviceInfoArray;+    int deviceInfoInitializationSucceeded;+    PaTime defaultLowLatency, defaultHighLatency;+    DWORD waveInPreferredDevice, waveOutPreferredDevice;+    DWORD preferredDeviceStatusFlags;++    winMmeHostApi = (PaWinMmeHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinMmeHostApiRepresentation) );+    if( !winMmeHostApi )+    {+        result = paInsufficientMemory;+        goto error;+    }++    winMmeHostApi->allocations = PaUtil_CreateAllocationGroup();+    if( !winMmeHostApi->allocations )+    {+        result = paInsufficientMemory;+        goto error;+    }++    *hostApi = &winMmeHostApi->inheritedHostApiRep;+    (*hostApi)->info.structVersion = 1;+    (*hostApi)->info.type = paMME;+    (*hostApi)->info.name = "MME";++    +    /* initialise device counts and default devices under the assumption that+        there are no devices. These values are incremented below if and when+        devices are successfully initialized.+    */+    (*hostApi)->info.deviceCount = 0;+    (*hostApi)->info.defaultInputDevice = paNoDevice;+    (*hostApi)->info.defaultOutputDevice = paNoDevice;+    winMmeHostApi->inputDeviceCount = 0;+    winMmeHostApi->outputDeviceCount = 0;++#if !defined(DRVM_MAPPER_PREFERRED_GET)+/* DRVM_MAPPER_PREFERRED_GET is defined in mmddk.h but we avoid a dependency on the DDK by defining it here */+#define DRVM_MAPPER_PREFERRED_GET    (0x2000+21)+#endif++    /* the following calls assume that if wave*Message fails the preferred device parameter won't be modified */+    preferredDeviceStatusFlags = 0;+    waveInPreferredDevice = -1;+    waveInMessage( (HWAVEIN)WAVE_MAPPER, DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveInPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );++    preferredDeviceStatusFlags = 0;+    waveOutPreferredDevice = -1;+    waveOutMessage( (HWAVEOUT)WAVE_MAPPER, DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveOutPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );++    maximumPossibleDeviceCount = 0;++    inputDeviceCount = waveInGetNumDevs();+    if( inputDeviceCount > 0 )+    	maximumPossibleDeviceCount += inputDeviceCount + 1;	/* assume there is a WAVE_MAPPER */++    outputDeviceCount = waveOutGetNumDevs();+    if( outputDeviceCount > 0 )+	    maximumPossibleDeviceCount += outputDeviceCount + 1;	/* assume there is a WAVE_MAPPER */+++    if( maximumPossibleDeviceCount > 0 ){++        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(+                winMmeHostApi->allocations, sizeof(PaDeviceInfo*) * maximumPossibleDeviceCount );+        if( !(*hostApi)->deviceInfos )+        {+            result = paInsufficientMemory;+            goto error;+        }++        /* allocate all device info structs in a contiguous block */+        deviceInfoArray = (PaWinMmeDeviceInfo*)PaUtil_GroupAllocateMemory(+                winMmeHostApi->allocations, sizeof(PaWinMmeDeviceInfo) * maximumPossibleDeviceCount );+        if( !deviceInfoArray )+        {+            result = paInsufficientMemory;+            goto error;+        }++        winMmeHostApi->winMmeDeviceIds = (UINT*)PaUtil_GroupAllocateMemory(+                winMmeHostApi->allocations, sizeof(int) * maximumPossibleDeviceCount );+        if( !winMmeHostApi->winMmeDeviceIds )+        {+            result = paInsufficientMemory;+            goto error;+        }++        GetDefaultLatencies( &defaultLowLatency, &defaultHighLatency );++        if( inputDeviceCount > 0 ){+            /* -1 is the WAVE_MAPPER */+            for( i = -1; i < inputDeviceCount; ++i ){+                UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);+                PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];+                PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;+                deviceInfo->structVersion = 2;+                deviceInfo->hostApi = hostApiIndex;++                deviceInfo->maxInputChannels = 0;+                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;+                deviceInfo->maxOutputChannels = 0;+                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;++                deviceInfo->defaultLowInputLatency = defaultLowLatency;+                deviceInfo->defaultLowOutputLatency = defaultLowLatency;+                deviceInfo->defaultHighInputLatency = defaultHighLatency;+                deviceInfo->defaultHighOutputLatency = defaultHighLatency;++                result = InitializeInputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,+                        winMmeDeviceId, &deviceInfoInitializationSucceeded );+                if( result != paNoError )+                    goto error;++                if( deviceInfoInitializationSucceeded ){+                    if( (*hostApi)->info.defaultInputDevice == paNoDevice ){+                        /* if there is currently no default device, use the first one available */+                        (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;+                    +                    }else if( winMmeDeviceId == waveInPreferredDevice ){+                        /* set the default device to the system preferred device */+                        (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;+                    }++                    winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;+                    (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;++                    winMmeHostApi->inputDeviceCount++;+                    (*hostApi)->info.deviceCount++;+                }+            }+        }++        if( outputDeviceCount > 0 ){+            /* -1 is the WAVE_MAPPER */+            for( i = -1; i < outputDeviceCount; ++i ){+                UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);+                PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];+                PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;+                deviceInfo->structVersion = 2;+                deviceInfo->hostApi = hostApiIndex;++                deviceInfo->maxInputChannels = 0;+                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;+                deviceInfo->maxOutputChannels = 0;+                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;++                deviceInfo->defaultLowInputLatency = defaultLowLatency;+                deviceInfo->defaultLowOutputLatency = defaultLowLatency;+                deviceInfo->defaultHighInputLatency = defaultHighLatency;+                deviceInfo->defaultHighOutputLatency = defaultHighLatency; ++                result = InitializeOutputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,+                        winMmeDeviceId, &deviceInfoInitializationSucceeded );+                if( result != paNoError )+                    goto error;++                if( deviceInfoInitializationSucceeded ){+                    if( (*hostApi)->info.defaultOutputDevice == paNoDevice ){+                        /* if there is currently no default device, use the first one available */+                        (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;++                    }else if( winMmeDeviceId == waveOutPreferredDevice ){+                        /* set the default device to the system preferred device */+                        (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;+                    }++                    winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;+                    (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;++                    winMmeHostApi->outputDeviceCount++;+                    (*hostApi)->info.deviceCount++;+                }+            }+        }+    }+    +    InitializeDefaultDeviceIdsFromEnv( winMmeHostApi );++    (*hostApi)->Terminate = Terminate;+    (*hostApi)->OpenStream = OpenStream;+    (*hostApi)->IsFormatSupported = IsFormatSupported;++    PaUtil_InitializeStreamInterface( &winMmeHostApi->callbackStreamInterface, CloseStream, StartStream,+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,+                                      GetStreamTime, GetStreamCpuLoad,+                                      PaUtil_DummyRead, PaUtil_DummyWrite,+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );++    PaUtil_InitializeStreamInterface( &winMmeHostApi->blockingStreamInterface, CloseStream, StartStream,+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );++    return result;++error:+    if( winMmeHostApi )+    {+        if( winMmeHostApi->allocations )+        {+            PaUtil_FreeAllAllocations( winMmeHostApi->allocations );+            PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );+        }+        +        PaUtil_FreeMemory( winMmeHostApi );+    }++    return result;+}+++static void Terminate( struct PaUtilHostApiRepresentation *hostApi )+{+    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;++    if( winMmeHostApi->allocations )+    {+        PaUtil_FreeAllAllocations( winMmeHostApi->allocations );+        PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );+    }++    PaUtil_FreeMemory( winMmeHostApi );+}+++static PaError IsInputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )+{+    PaError result = paNoError;++    if( channelCount > 0+            && deviceInfo->deviceInputChannelCountIsKnown+            && channelCount > deviceInfo->inheritedDeviceInfo.maxInputChannels ){++        result = paInvalidChannelCount; +    }++    return result;+}++static PaError IsOutputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )+{+    PaError result = paNoError;++    if( channelCount > 0+            && deviceInfo->deviceOutputChannelCountIsKnown+            && channelCount > deviceInfo->inheritedDeviceInfo.maxOutputChannels ){++        result = paInvalidChannelCount; +    }++    return result;+}++static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,+                                  const PaStreamParameters *inputParameters,+                                  const PaStreamParameters *outputParameters,+                                  double sampleRate )+{+    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;+    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;+    int inputChannelCount, outputChannelCount;+    int inputMultipleDeviceChannelCount, outputMultipleDeviceChannelCount;+    PaSampleFormat inputSampleFormat, outputSampleFormat;+    PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;+    UINT winMmeInputDeviceId, winMmeOutputDeviceId;+    unsigned int i;+    PaError paerror;++    /* The calls to QueryFormatSupported below are intended to detect invalid+        sample rates. If we assume that the channel count and format are OK,+        then the only thing that could fail is the sample rate. This isn't+        strictly true, but I can't think of a better way to test that the+        sample rate is valid.+    */  +    +    if( inputParameters )+    {+        inputChannelCount = inputParameters->channelCount;+        inputSampleFormat = inputParameters->sampleFormat;+        inputStreamInfo = inputParameters->hostApiSpecificStreamInfo;+        +        /* all standard sample formats are supported by the buffer adapter,+             this implementation doesn't support any custom sample formats */+        if( inputSampleFormat & paCustomFormat )+            return paSampleFormatNotSupported;++        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification+                && inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )+        {+            inputMultipleDeviceChannelCount = 0;+            for( i=0; i< inputStreamInfo->deviceCount; ++i )+            {+                inputMultipleDeviceChannelCount += inputStreamInfo->devices[i].channelCount;+                    +                inputDeviceInfo = hostApi->deviceInfos[ inputStreamInfo->devices[i].device ];++                /* check that input device can support inputChannelCount */+                if( inputStreamInfo->devices[i].channelCount < 1 )+                    return paInvalidChannelCount;++                paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo, +                        inputStreamInfo->devices[i].channelCount );+                if( paerror != paNoError )+                    return paerror;++                /* test for valid sample rate, see comment above */+                winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputStreamInfo->devices[i].device );+                paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, +                        winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate, +                        ((inputStreamInfo) ? inputStreamInfo->flags : 0) );+                if( paerror != paNoError )+                    return paInvalidSampleRate;+            }+                +            if( inputMultipleDeviceChannelCount != inputChannelCount )+                return paIncompatibleHostApiSpecificStreamInfo;                  +        }+        else+        {+            if( inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )+                return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the input device */++            inputDeviceInfo = hostApi->deviceInfos[ inputParameters->device ];++            /* check that input device can support inputChannelCount */+            paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo, inputChannelCount );+            if( paerror != paNoError )+                return paerror;++            /* test for valid sample rate, see comment above */+            winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputParameters->device );+            paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, +                    winMmeInputDeviceId, inputChannelCount, sampleRate,+                    ((inputStreamInfo) ? inputStreamInfo->flags : 0) );+            if( paerror != paNoError )+                return paInvalidSampleRate;+        }+    }++    if( outputParameters )+    {+        outputChannelCount = outputParameters->channelCount;+        outputSampleFormat = outputParameters->sampleFormat;+        outputStreamInfo = outputParameters->hostApiSpecificStreamInfo;++        /* all standard sample formats are supported by the buffer adapter,+            this implementation doesn't support any custom sample formats */+        if( outputSampleFormat & paCustomFormat )+            return paSampleFormatNotSupported;++        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification+                && outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )+        {+            outputMultipleDeviceChannelCount = 0;+            for( i=0; i< outputStreamInfo->deviceCount; ++i )+            {+                outputMultipleDeviceChannelCount += outputStreamInfo->devices[i].channelCount;+                    +                outputDeviceInfo = hostApi->deviceInfos[ outputStreamInfo->devices[i].device ];++                /* check that output device can support outputChannelCount */+                if( outputStreamInfo->devices[i].channelCount < 1 )+                    return paInvalidChannelCount;++                paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo, +                        outputStreamInfo->devices[i].channelCount );+                if( paerror != paNoError )+                    return paerror;++                /* test for valid sample rate, see comment above */+                winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputStreamInfo->devices[i].device );+                paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, +                        winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate,+                        ((outputStreamInfo) ? outputStreamInfo->flags : 0) );+                if( paerror != paNoError )+                    return paInvalidSampleRate;+            }+                +            if( outputMultipleDeviceChannelCount != outputChannelCount )+                return paIncompatibleHostApiSpecificStreamInfo;            +        }+        else+        {+            if( outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )+                return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the output device */++            outputDeviceInfo = hostApi->deviceInfos[ outputParameters->device ];++            /* check that output device can support outputChannelCount */+            paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo, outputChannelCount );+            if( paerror != paNoError )+                return paerror;++            /* test for valid sample rate, see comment above */+            winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputParameters->device );+            paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, +                    winMmeOutputDeviceId, outputChannelCount, sampleRate,+                    ((outputStreamInfo) ? outputStreamInfo->flags : 0) );+            if( paerror != paNoError )+                return paInvalidSampleRate;+        }+    }+    +    /*+            - if a full duplex stream is requested, check that the combination+                of input and output parameters is supported++            - check that the device supports sampleRate++            for mme all we can do is test that the input and output devices+            support the requested sample rate and number of channels. we+            cannot test for full duplex compatibility.+    */                                             ++    return paFormatIsSupported;+}+++static unsigned long ComputeHostBufferCountForFixedBufferSizeFrames(+        unsigned long suggestedLatencyFrames,+        unsigned long hostBufferSizeFrames,+        unsigned long minimumBufferCount )+{+    /* Calculate the number of buffers of length hostFramesPerBuffer +       that fit in suggestedLatencyFrames, rounding up to the next integer.++       The value (hostBufferSizeFrames - 1) below is to ensure the buffer count is rounded up.+    */+    unsigned long resultBufferCount = ((suggestedLatencyFrames + (hostBufferSizeFrames - 1)) / hostBufferSizeFrames);++    /* We always need one extra buffer for processing while the rest are queued/playing.+       i.e. latency is framesPerBuffer * (bufferCount - 1)+    */+    resultBufferCount += 1;++    if( resultBufferCount < minimumBufferCount ) /* clamp to minimum buffer count */+        resultBufferCount = minimumBufferCount;++    return resultBufferCount;+}+++static unsigned long ComputeHostBufferSizeGivenHardUpperLimit( +        unsigned long userFramesPerBuffer,+        unsigned long absoluteMaximumBufferSizeFrames )+{+    static unsigned long primes_[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, +            29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 0 }; /* zero terminated */++    unsigned long result = userFramesPerBuffer;+    int i;++    assert( absoluteMaximumBufferSizeFrames > 67 ); /* assume maximum is large and we're only factoring by small primes */++    /* search for the largest integer factor of userFramesPerBuffer less +       than or equal to absoluteMaximumBufferSizeFrames */++    /* repeatedly divide by smallest prime factors until a buffer size +       smaller than absoluteMaximumBufferSizeFrames is found */+    while( result > absoluteMaximumBufferSizeFrames ){++        /* search for the smallest prime factor of result */+        for( i=0; primes_[i] != 0; ++i ) +        {+            unsigned long p = primes_[i];+            unsigned long divided = result / p;+            if( divided*p == result )+            {+                result = divided;+                break; /* continue with outer while loop */+            }+        }+        if( primes_[i] == 0 )+        { /* loop failed to find a prime factor, return an approximate result */+            unsigned long d = (userFramesPerBuffer + (absoluteMaximumBufferSizeFrames-1))+                    / absoluteMaximumBufferSizeFrames;+            return userFramesPerBuffer / d;+        }+    }++    return result;+}+++static PaError SelectHostBufferSizeFramesAndHostBufferCount(+        unsigned long suggestedLatencyFrames,+        unsigned long userFramesPerBuffer,+        unsigned long minimumBufferCount,+        unsigned long preferredMaximumBufferSizeFrames, /* try not to exceed this. for example, don't exceed when coalescing buffers */+        unsigned long absoluteMaximumBufferSizeFrames,  /* never exceed this, a hard limit */+        unsigned long *hostBufferSizeFrames,+        unsigned long *hostBufferCount )+{+    unsigned long effectiveUserFramesPerBuffer;+    unsigned long numberOfUserBuffersPerHostBuffer;+++    if( userFramesPerBuffer == paFramesPerBufferUnspecified ){++        effectiveUserFramesPerBuffer = PA_MME_HOST_BUFFER_GRANULARITY_FRAMES_WHEN_UNSPECIFIED_;++    }else{++        if( userFramesPerBuffer > absoluteMaximumBufferSizeFrames ){++            /* user has requested a user buffer that's larger than absoluteMaximumBufferSizeFrames.+               try to choose a buffer size that is equal or smaller than absoluteMaximumBufferSizeFrames+               but is also an integer factor of userFramesPerBuffer, so as to distribute computation evenly.+               the buffer processor will handle the block adaption between host and user buffer sizes.+               see http://www.portaudio.com/trac/ticket/189 for discussion.+            */++            effectiveUserFramesPerBuffer = ComputeHostBufferSizeGivenHardUpperLimit( userFramesPerBuffer, absoluteMaximumBufferSizeFrames );+            assert( effectiveUserFramesPerBuffer <= absoluteMaximumBufferSizeFrames );++            /* try to ensure that duration of host buffering is at least as +                large as duration of user buffer. */+            if( suggestedLatencyFrames < userFramesPerBuffer )+                suggestedLatencyFrames = userFramesPerBuffer; ++        }else{++            effectiveUserFramesPerBuffer = userFramesPerBuffer;+        }+    }+                        +    /* compute a host buffer count based on suggestedLatencyFrames and our granularity */++    *hostBufferSizeFrames = effectiveUserFramesPerBuffer;++    *hostBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(+            suggestedLatencyFrames, *hostBufferSizeFrames, minimumBufferCount );++    if( *hostBufferSizeFrames >= userFramesPerBuffer )+    {+        /*+            If there are too many host buffers we would like to coalesce +            them by packing an integer number of user buffers into each host buffer.+            We try to coalesce such that hostBufferCount will lie between +            PA_MME_TARGET_HOST_BUFFER_COUNT_ and (PA_MME_TARGET_HOST_BUFFER_COUNT_*2)-1.+            We limit coalescing to avoid exceeding either absoluteMaximumBufferSizeFrames and+            preferredMaximumBufferSizeFrames. ++            First, compute a coalescing factor: the number of user buffers per host buffer.+            The goal is to achieve PA_MME_TARGET_HOST_BUFFER_COUNT_ total buffer count.+            Since our latency is computed based on (*hostBufferCount - 1) we compute a+            coalescing factor based on (*hostBufferCount - 1) and (PA_MME_TARGET_HOST_BUFFER_COUNT_-1).++            The + (PA_MME_TARGET_HOST_BUFFER_COUNT_-2) term below is intended to round up.+        */+        numberOfUserBuffersPerHostBuffer = ((*hostBufferCount - 1) + (PA_MME_TARGET_HOST_BUFFER_COUNT_-2)) / (PA_MME_TARGET_HOST_BUFFER_COUNT_ - 1);+        +        if( numberOfUserBuffersPerHostBuffer > 1 )+        {+            unsigned long maxCoalescedBufferSizeFrames = (absoluteMaximumBufferSizeFrames < preferredMaximumBufferSizeFrames) /* minimum of our limits */+                            ? absoluteMaximumBufferSizeFrames+                            : preferredMaximumBufferSizeFrames;++            unsigned long maxUserBuffersPerHostBuffer = maxCoalescedBufferSizeFrames / effectiveUserFramesPerBuffer; /* don't coalesce more than this */++            if( numberOfUserBuffersPerHostBuffer > maxUserBuffersPerHostBuffer )+                numberOfUserBuffersPerHostBuffer = maxUserBuffersPerHostBuffer;++            *hostBufferSizeFrames = effectiveUserFramesPerBuffer * numberOfUserBuffersPerHostBuffer;++            /* recompute hostBufferCount to approximate suggestedLatencyFrames now that hostBufferSizeFrames is larger */+            *hostBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(+                    suggestedLatencyFrames, *hostBufferSizeFrames, minimumBufferCount );+        }+    }++    return paNoError;+}+++static PaError CalculateMaxHostSampleFrameSizeBytes(+        int channelCount,+        PaSampleFormat hostSampleFormat,+        const PaWinMmeStreamInfo *streamInfo,+        int *hostSampleFrameSizeBytes )+{+    unsigned int i;+    /* PA WMME streams may aggregate multiple WMME devices. When the stream addresses +       more than one device in a single direction, maxDeviceChannelCount is the maximum +       number of channels used by a single device.+    */+    int maxDeviceChannelCount = channelCount;+    int hostSampleSizeBytes = Pa_GetSampleSize( hostSampleFormat );+    if( hostSampleSizeBytes < 0 )+    {+        return hostSampleSizeBytes; /* the value of hostSampleSize here is an error code, not a sample size */+    }++    if( streamInfo && ( streamInfo->flags & paWinMmeUseMultipleDevices ) )+    {+        maxDeviceChannelCount = streamInfo->devices[0].channelCount;+        for( i=1; i< streamInfo->deviceCount; ++i )+        {+            if( streamInfo->devices[i].channelCount > maxDeviceChannelCount )+                maxDeviceChannelCount = streamInfo->devices[i].channelCount;+        }+    }++    *hostSampleFrameSizeBytes = hostSampleSizeBytes * maxDeviceChannelCount;++    return paNoError;+}+++/* CalculateBufferSettings() fills the framesPerHostInputBuffer, hostInputBufferCount,+   framesPerHostOutputBuffer and hostOutputBufferCount parameters based on the values+   of the other parameters.+*/++static PaError CalculateBufferSettings(+        unsigned long *hostFramesPerInputBuffer, unsigned long *hostInputBufferCount,+        unsigned long *hostFramesPerOutputBuffer, unsigned long *hostOutputBufferCount,+        int inputChannelCount, PaSampleFormat hostInputSampleFormat,+        PaTime suggestedInputLatency, const PaWinMmeStreamInfo *inputStreamInfo,+        int outputChannelCount, PaSampleFormat hostOutputSampleFormat,+        PaTime suggestedOutputLatency, const PaWinMmeStreamInfo *outputStreamInfo,+        double sampleRate, unsigned long userFramesPerBuffer )+{+    PaError result = paNoError;+    +    if( inputChannelCount > 0 ) /* stream has input */+    {+        int hostInputFrameSizeBytes;+        result = CalculateMaxHostSampleFrameSizeBytes( +                inputChannelCount, hostInputSampleFormat, inputStreamInfo, &hostInputFrameSizeBytes );+        if( result != paNoError )+            goto error;++        if( inputStreamInfo+                && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )+        {+            /* input - using low level latency parameters if provided */++            if( inputStreamInfo->bufferCount <= 0+                    || inputStreamInfo->framesPerBuffer <= 0 )+            {+                result = paIncompatibleHostApiSpecificStreamInfo;+                goto error;+            }++            *hostFramesPerInputBuffer = inputStreamInfo->framesPerBuffer;+            *hostInputBufferCount = inputStreamInfo->bufferCount;+        }+        else+        {+            /* input - not using low level latency parameters, so compute +               hostFramesPerInputBuffer and hostInputBufferCount+               based on userFramesPerBuffer and suggestedInputLatency. */++            unsigned long minimumBufferCount = (outputChannelCount > 0)+                    ? PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_+                    : PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_;++            result = SelectHostBufferSizeFramesAndHostBufferCount(+                    (unsigned long)(suggestedInputLatency * sampleRate), /* (truncate) */+                    userFramesPerBuffer,+                    minimumBufferCount,+                    (unsigned long)(PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate), /* in frames. preferred maximum */+                    (PA_MME_MAX_HOST_BUFFER_BYTES_ / hostInputFrameSizeBytes),  /* in frames. a hard limit. note truncation due to +                                                                                division is intentional here to limit max bytes */+                    hostFramesPerInputBuffer,+                    hostInputBufferCount );+            if( result != paNoError )+                goto error;+        }+    }+    else+    {+        *hostFramesPerInputBuffer = 0;+        *hostInputBufferCount = 0;+    }++    if( outputChannelCount > 0 ) /* stream has output */+    {+        if( outputStreamInfo+                && ( outputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )+        {+            /* output - using low level latency parameters */++            if( outputStreamInfo->bufferCount <= 0+                    || outputStreamInfo->framesPerBuffer <= 0 )+            {+                result = paIncompatibleHostApiSpecificStreamInfo;+                goto error;+            }++            *hostFramesPerOutputBuffer = outputStreamInfo->framesPerBuffer;+            *hostOutputBufferCount = outputStreamInfo->bufferCount;++            if( inputChannelCount > 0 ) /* full duplex */+            {+                /* harmonize hostFramesPerInputBuffer and hostFramesPerOutputBuffer */++                if( *hostFramesPerInputBuffer != *hostFramesPerOutputBuffer )+                {+                    if( inputStreamInfo+                            && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )+                    { +                        /* a custom StreamInfo was used for specifying both input+                            and output buffer sizes. We require that the larger buffer size+                            must be a multiple of the smaller buffer size */++                        if( *hostFramesPerInputBuffer < *hostFramesPerOutputBuffer )+                        {+                            if( *hostFramesPerOutputBuffer % *hostFramesPerInputBuffer != 0 )+                            {+                                result = paIncompatibleHostApiSpecificStreamInfo;+                                goto error;+                            }+                        }+                        else+                        {+                            assert( *hostFramesPerInputBuffer > *hostFramesPerOutputBuffer );+                            if( *hostFramesPerInputBuffer % *hostFramesPerOutputBuffer != 0 )+                            {+                                result = paIncompatibleHostApiSpecificStreamInfo;+                                goto error;+                            }+                        }                        +                    }+                    else+                    {+                        /* a custom StreamInfo was not used for specifying the input buffer size,+                            so use the output buffer size, and approximately the suggested input latency. */++                        *hostFramesPerInputBuffer = *hostFramesPerOutputBuffer;++                        *hostInputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(+                                (unsigned long)(suggestedInputLatency * sampleRate), +                                *hostFramesPerInputBuffer, +                                PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ );+                    }+                }+            }+        }+        else+        {+            /* output - no low level latency parameters, so compute hostFramesPerOutputBuffer and hostOutputBufferCount+                based on userFramesPerBuffer and suggestedOutputLatency. */++            int hostOutputFrameSizeBytes;+            result = CalculateMaxHostSampleFrameSizeBytes( +                    outputChannelCount, hostOutputSampleFormat, outputStreamInfo, &hostOutputFrameSizeBytes );+            if( result != paNoError )+                goto error;++            /* compute the output buffer size and count */++            result = SelectHostBufferSizeFramesAndHostBufferCount(+                    (unsigned long)(suggestedOutputLatency * sampleRate), /* (truncate) */+                    userFramesPerBuffer,+                    PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_,+                    (unsigned long)(PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate), /* in frames. preferred maximum */+                    (PA_MME_MAX_HOST_BUFFER_BYTES_ / hostOutputFrameSizeBytes),  /* in frames. a hard limit. note truncation due to +                                                                                 division is intentional here to limit max bytes */+                    hostFramesPerOutputBuffer,+                    hostOutputBufferCount );+            if( result != paNoError )+                goto error;++            if( inputChannelCount > 0 ) /* full duplex */+            {+                /* harmonize hostFramesPerInputBuffer and hostFramesPerOutputBuffer */++                /* ensure that both input and output buffer sizes are the same.+                    if they don't match at this stage, choose the smallest one+                    and use that for input and output and recompute the corresponding+                    buffer count accordingly.+                */++                if( *hostFramesPerOutputBuffer != *hostFramesPerInputBuffer )+                {+                    if( hostFramesPerInputBuffer < hostFramesPerOutputBuffer )+                    {+                        *hostFramesPerOutputBuffer = *hostFramesPerInputBuffer;++                        *hostOutputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(+                                (unsigned long)(suggestedOutputLatency * sampleRate), +                                *hostOutputBufferCount, +                                PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ );+                    }+                    else+                    {+                        *hostFramesPerInputBuffer = *hostFramesPerOutputBuffer;++                        *hostInputBufferCount = ComputeHostBufferCountForFixedBufferSizeFrames(+                                (unsigned long)(suggestedInputLatency * sampleRate), +                                *hostFramesPerInputBuffer, +                                PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ );+                    }+                }   +            }+        }+    }+    else+    {+        *hostFramesPerOutputBuffer = 0;+        *hostOutputBufferCount = 0;+    }++error:+    return result;+}+++typedef struct+{+    HANDLE bufferEvent;+    void *waveHandles;+    unsigned int deviceCount;+    /* unsigned int channelCount; */+    WAVEHDR **waveHeaders;                  /* waveHeaders[device][buffer] */+    unsigned int bufferCount;+    unsigned int currentBufferIndex;+    unsigned int framesPerBuffer;+    unsigned int framesUsedInCurrentBuffer;+}PaWinMmeSingleDirectionHandlesAndBuffers;++/* prototypes for functions operating on PaWinMmeSingleDirectionHandlesAndBuffers */++static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers );+static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,+        PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,+        unsigned long winMmeSpecificFlags,+        unsigned long bytesPerHostSample,+        double sampleRate, PaWinMmeDeviceAndChannelCount *devices,+        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput );+static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError );+static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,+        unsigned long hostBufferCount,+        PaSampleFormat hostSampleFormat,+        unsigned long framesPerHostBuffer,+        PaWinMmeDeviceAndChannelCount *devices,+        int isInput );+static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput );+++static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )+{+    handlesAndBuffers->bufferEvent = 0;+    handlesAndBuffers->waveHandles = 0;+    handlesAndBuffers->deviceCount = 0;+    handlesAndBuffers->waveHeaders = 0;+    handlesAndBuffers->bufferCount = 0;+}    ++static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,+        PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,+        unsigned long winMmeSpecificFlags,+        unsigned long bytesPerHostSample,+        double sampleRate, PaWinMmeDeviceAndChannelCount *devices,+        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput )+{+    PaError result;+    MMRESULT mmresult;+    signed int i, j;+    PaSampleFormat sampleFormat;+    int waveFormatTag;++    /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()+        has already been called to zero some fields */       ++    result = CreateEventWithPaError( &handlesAndBuffers->bufferEvent, NULL, FALSE, FALSE, NULL );+    if( result != paNoError ) goto error;++    if( isInput )+        handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEIN) * deviceCount );+    else+        handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEOUT) * deviceCount );+    if( !handlesAndBuffers->waveHandles )+    {+        result = paInsufficientMemory;+        goto error;+    }++    handlesAndBuffers->deviceCount = deviceCount;++    for( i = 0; i < (signed int)deviceCount; ++i )+    {+        if( isInput )+            ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] = 0;+        else+            ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] = 0;+    }++    /* @todo at the moment we only use 16 bit sample format */+    sampleFormat = paInt16;+    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );++    for( i = 0; i < (signed int)deviceCount; ++i )+    {+        PaWinWaveFormat waveFormat;+        UINT winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device );+    +        /* @todo: consider providing a flag or #define to not try waveformat extensible +           this could just initialize j to 1 the first time round. */++        for( j = 0; j < 2; ++j )+        {+            switch(j){+                case 0:     +                    /* first, attempt to open the device using WAVEFORMATEXTENSIBLE, +                        if this fails we fall back to WAVEFORMATEX */++                    PaWin_InitializeWaveFormatExtensible( &waveFormat, devices[i].channelCount, +                            sampleFormat, waveFormatTag, sampleRate, channelMask );+                    break;+                +                case 1:+                    /* retry with WAVEFORMATEX */++                    PaWin_InitializeWaveFormatEx( &waveFormat, devices[i].channelCount, +                            sampleFormat, waveFormatTag, sampleRate );+                    break;+            }++            /* REVIEW: consider not firing an event for input when a full duplex+                stream is being used. this would probably depend on the+                neverDropInput flag. */++            if( isInput )+            {+                mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, +                                    (WAVEFORMATEX*)&waveFormat,+                               (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );+            }+            else+            {+                mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, +                                    (WAVEFORMATEX*)&waveFormat,+                                (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );+            }++            if( mmresult == MMSYSERR_NOERROR )+            {+                break; /* success */+            }+            else if( j == 0 )+            {+                continue; /* try again with WAVEFORMATEX */+            }+            else+            {+                switch( mmresult )+                {+                    case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */+                        result = paDeviceUnavailable;+                        break;+                    case MMSYSERR_NODRIVER:	    /* No device driver is present. */+                        result = paDeviceUnavailable;+                        break;+                    case MMSYSERR_NOMEM:	    /* Unable to allocate or lock memory. */+                        result = paInsufficientMemory;+                        break;++                    case MMSYSERR_BADDEVICEID:	/* Specified device identifier is out of range. */+                        /* falls through */++                    case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */+                                                    /* This can also occur if we try to open the device with an unsupported+                                                     * number of channels. This is attempted when device*ChannelCountIsKnown is+                                                     * set to 0. +                                                     */+                        /* falls through */+                    default:+                        result = paUnanticipatedHostError;+                        if( isInput )+                        {+                            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+                        }+                        else+                        {+                            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+                        }+                }+                goto error;+            }+        }+    }++    return result;++error:+    TerminateWaveHandles( handlesAndBuffers, isInput, 1 /* currentlyProcessingAnError */ );++    return result;+}+++static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError )+{+    PaError result = paNoError;+    MMRESULT mmresult;+    signed int i;+    +    if( handlesAndBuffers->waveHandles )+    {+        for( i = handlesAndBuffers->deviceCount-1; i >= 0; --i )+        {+            if( isInput )+            {+                if( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] )+                    mmresult = waveInClose( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] );+                else+                    mmresult = MMSYSERR_NOERROR;+            }+            else+            {+                if( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] )+                    mmresult = waveOutClose( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] );+                else+                    mmresult = MMSYSERR_NOERROR;+            }++            if( mmresult != MMSYSERR_NOERROR &&+                !currentlyProcessingAnError ) /* don't update the error state if we're already processing an error */+            {+                result = paUnanticipatedHostError;+                if( isInput )+                {+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+                }+                else+                {+                    PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+                }+                /* note that we don't break here, we try to continue closing devices */+            }+        }++        PaUtil_FreeMemory( handlesAndBuffers->waveHandles );+        handlesAndBuffers->waveHandles = 0;+    }++    if( handlesAndBuffers->bufferEvent )+    {+        result = CloseHandleWithPaError( handlesAndBuffers->bufferEvent );+        handlesAndBuffers->bufferEvent = 0;+    }+    +    return result;+}+++static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,+        unsigned long hostBufferCount,+        PaSampleFormat hostSampleFormat,+        unsigned long framesPerHostBuffer,+        PaWinMmeDeviceAndChannelCount *devices,+        int isInput )+{+    PaError result = paNoError;+    MMRESULT mmresult;+    WAVEHDR *deviceWaveHeaders;+    signed int i, j;++    /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()+        has already been called to zero some fields */+        ++    /* allocate an array of pointers to arrays of wave headers, one array of+        wave headers per device */+    handlesAndBuffers->waveHeaders = (WAVEHDR**)PaUtil_AllocateMemory( sizeof(WAVEHDR*) * handlesAndBuffers->deviceCount );+    if( !handlesAndBuffers->waveHeaders )+    {+        result = paInsufficientMemory;+        goto error;+    }+    +    for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )+        handlesAndBuffers->waveHeaders[i] = 0;++    handlesAndBuffers->bufferCount = hostBufferCount;++    for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )+    {+        int bufferBytes = Pa_GetSampleSize( hostSampleFormat ) *+                framesPerHostBuffer * devices[i].channelCount;+        if( bufferBytes < 0 )+        {+            result = paInternalError;+            goto error;+        }++        /* Allocate an array of wave headers for device i */+        deviceWaveHeaders = (WAVEHDR *) PaUtil_AllocateMemory( sizeof(WAVEHDR)*hostBufferCount );+        if( !deviceWaveHeaders )+        {+            result = paInsufficientMemory;+            goto error;+        }++        for( j=0; j < (signed int)hostBufferCount; ++j )+            deviceWaveHeaders[j].lpData = 0;++        handlesAndBuffers->waveHeaders[i] = deviceWaveHeaders;++        /* Allocate a buffer for each wave header */+        for( j=0; j < (signed int)hostBufferCount; ++j )+        {+            deviceWaveHeaders[j].lpData = (char *)PaUtil_AllocateMemory( bufferBytes );+            if( !deviceWaveHeaders[j].lpData )+            {+                result = paInsufficientMemory;+                goto error;+            }+            deviceWaveHeaders[j].dwBufferLength = bufferBytes;+            deviceWaveHeaders[j].dwUser = 0xFFFFFFFF; /* indicates that *PrepareHeader() has not yet been called, for error clean up code */++            if( isInput )+            {+                mmresult = waveInPrepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );+                if( mmresult != MMSYSERR_NOERROR )+                {+                    result = paUnanticipatedHostError;+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+                    goto error;+                }+            }+            else /* output */+            {+                mmresult = waveOutPrepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );+                if( mmresult != MMSYSERR_NOERROR )+                {+                    result = paUnanticipatedHostError;+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+                    goto error;+                }+            }+            deviceWaveHeaders[j].dwUser = devices[i].channelCount;+        }+    }++    return result;++error:+    TerminateWaveHeaders( handlesAndBuffers, isInput );+    +    return result;+}+++static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput )+{+    signed int i, j;+    WAVEHDR *deviceWaveHeaders;+    +    if( handlesAndBuffers->waveHeaders )+    {+        for( i = handlesAndBuffers->deviceCount-1; i >= 0 ; --i )+        {+            deviceWaveHeaders = handlesAndBuffers->waveHeaders[i];  /* wave headers for device i */+            if( deviceWaveHeaders )+            {+                for( j = handlesAndBuffers->bufferCount-1; j >= 0; --j )+                {+                    if( deviceWaveHeaders[j].lpData )+                    {+                        if( deviceWaveHeaders[j].dwUser != 0xFFFFFFFF )+                        {+                            if( isInput )+                                waveInUnprepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );+                            else+                                waveOutUnprepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );+                        }++                        PaUtil_FreeMemory( deviceWaveHeaders[j].lpData );+                    }+                }++                PaUtil_FreeMemory( deviceWaveHeaders );+            }+        }++        PaUtil_FreeMemory( handlesAndBuffers->waveHeaders );+        handlesAndBuffers->waveHeaders = 0;+    }+}++++/* PaWinMmeStream - a stream data structure specifically for this implementation */+/* note that struct PaWinMmeStream is typedeffed to PaWinMmeStream above. */+struct PaWinMmeStream+{+    PaUtilStreamRepresentation streamRepresentation;+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;+    PaUtilBufferProcessor bufferProcessor;++    int primeStreamUsingCallback;++    PaWinMmeSingleDirectionHandlesAndBuffers input;+    PaWinMmeSingleDirectionHandlesAndBuffers output;++    /* Processing thread management -------------- */+    HANDLE abortEvent;+    HANDLE processingThread;+    PA_THREAD_ID processingThreadId;++    char throttleProcessingThreadOnOverload; /* 0 -> don't throtte, non-0 -> throttle */+    int processingThreadPriority;+    int highThreadPriority;+    int throttledThreadPriority;+    unsigned long throttledSleepMsecs;++    int isStopped;+    volatile int isActive;+    volatile int stopProcessing; /* stop thread once existing buffers have been returned */+    volatile int abortProcessing; /* stop thread immediately */++    DWORD allBuffersDurationMs; /* used to calculate timeouts */+};++/* updates deviceCount if PaWinMmeUseMultipleDevices is used */++static PaError ValidateWinMmeSpecificStreamInfo(+        const PaStreamParameters *streamParameters,+        const PaWinMmeStreamInfo *streamInfo,+        unsigned long *winMmeSpecificFlags,+        char *throttleProcessingThreadOnOverload,+        unsigned long *deviceCount )+{+	if( streamInfo )+	{+	    if( streamInfo->size != sizeof( PaWinMmeStreamInfo )+	            || streamInfo->version != 1 )+	    {+	        return paIncompatibleHostApiSpecificStreamInfo;+	    }++        *winMmeSpecificFlags = streamInfo->flags;++	    if( streamInfo->flags & paWinMmeDontThrottleOverloadedProcessingThread )+	        *throttleProcessingThreadOnOverload = 0;+            +	    if( streamInfo->flags & paWinMmeUseMultipleDevices )+	    {+	        if( streamParameters->device != paUseHostApiSpecificDeviceSpecification )+	            return paInvalidDevice;+	+			*deviceCount = streamInfo->deviceCount;+		}	+	}++	return paNoError;+}++static PaError RetrieveDevicesFromStreamParameters(+        struct PaUtilHostApiRepresentation *hostApi,+        const PaStreamParameters *streamParameters,+        const PaWinMmeStreamInfo *streamInfo,+        PaWinMmeDeviceAndChannelCount *devices,+        unsigned long deviceCount )+{+    PaError result = paNoError;+    unsigned int i;+    int totalChannelCount;+    PaDeviceIndex hostApiDevice;+    +	if( streamInfo && streamInfo->flags & paWinMmeUseMultipleDevices )+	{+		totalChannelCount = 0;+	    for( i=0; i < deviceCount; ++i )+	    {+	        /* validate that the device number is within range */+	        result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice,+	                        streamInfo->devices[i].device, hostApi );+	        if( result != paNoError )+	            return result;+	        +	        devices[i].device = hostApiDevice;+	        devices[i].channelCount = streamInfo->devices[i].channelCount;+	+	        totalChannelCount += devices[i].channelCount;+	    }+	+	    if( totalChannelCount != streamParameters->channelCount )+	    {+	        /* channelCount must match total channels specified by multiple devices */+	        return paInvalidChannelCount; /* REVIEW use of this error code */+	    }+	}	+	else+	{		+	    devices[0].device = streamParameters->device;+	    devices[0].channelCount = streamParameters->channelCount;+	}++    return result;+}++static PaError ValidateInputChannelCounts(+        struct PaUtilHostApiRepresentation *hostApi,+        PaWinMmeDeviceAndChannelCount *devices,+        unsigned long deviceCount )+{+    unsigned int i;+    PaWinMmeDeviceInfo *inputDeviceInfo;+    PaError paerror;++	for( i=0; i < deviceCount; ++i )+	{+        if( devices[i].channelCount < 1 )+        	return paInvalidChannelCount;++        inputDeviceInfo = +                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];++        paerror = IsInputChannelCountSupported( inputDeviceInfo, devices[i].channelCount );+        if( paerror != paNoError )+            return paerror;+	}++    return paNoError;+}++static PaError ValidateOutputChannelCounts(+        struct PaUtilHostApiRepresentation *hostApi,+        PaWinMmeDeviceAndChannelCount *devices,+        unsigned long deviceCount )+{+    unsigned int i;+    PaWinMmeDeviceInfo *outputDeviceInfo;+    PaError paerror;++	for( i=0; i < deviceCount; ++i )+	{+        if( devices[i].channelCount < 1 )+        	return paInvalidChannelCount;++        outputDeviceInfo = +                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];++        paerror = IsOutputChannelCountSupported( outputDeviceInfo, devices[i].channelCount );+        if( paerror != paNoError )+            return paerror;+	}++    return paNoError;+}+++/* the following macros are intended to improve the readability of the following code */+#define PA_IS_INPUT_STREAM_( stream ) ( stream ->input.waveHandles )+#define PA_IS_OUTPUT_STREAM_( stream ) ( stream ->output.waveHandles )+#define PA_IS_FULL_DUPLEX_STREAM_( stream ) ( stream ->input.waveHandles && stream ->output.waveHandles )+#define PA_IS_HALF_DUPLEX_STREAM_( stream ) ( !(stream ->input.waveHandles && stream ->output.waveHandles) )++static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,+                           PaStream** s,+                           const PaStreamParameters *inputParameters,+                           const PaStreamParameters *outputParameters,+                           double sampleRate,+                           unsigned long framesPerBuffer,+                           PaStreamFlags streamFlags,+                           PaStreamCallback *streamCallback,+                           void *userData )+{+    PaError result;+    PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;+    PaWinMmeStream *stream = 0;+    int bufferProcessorIsInitialized = 0;+    int streamRepresentationIsInitialized = 0;+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;+    int inputChannelCount, outputChannelCount;+    PaSampleFormat inputSampleFormat, outputSampleFormat;+    double suggestedInputLatency, suggestedOutputLatency;+    PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;+    PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;+    unsigned long framesPerHostInputBuffer;+    unsigned long hostInputBufferCount;+    unsigned long framesPerHostOutputBuffer;+    unsigned long hostOutputBufferCount;+    unsigned long framesPerBufferProcessorCall;+    PaWinMmeDeviceAndChannelCount *inputDevices = 0;  /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */+    unsigned long winMmeSpecificInputFlags = 0;+    unsigned long inputDeviceCount = 0;            +    PaWinMmeDeviceAndChannelCount *outputDevices = 0;+    unsigned long winMmeSpecificOutputFlags = 0;+    unsigned long outputDeviceCount = 0;                /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */+    char throttleProcessingThreadOnOverload = 1;++    +    if( inputParameters )+    {+		inputChannelCount = inputParameters->channelCount;+        inputSampleFormat = inputParameters->sampleFormat;+        suggestedInputLatency = inputParameters->suggestedLatency;++      	inputDeviceCount = 1;++		/* validate input hostApiSpecificStreamInfo */+        inputStreamInfo = (PaWinMmeStreamInfo*)inputParameters->hostApiSpecificStreamInfo;+		result = ValidateWinMmeSpecificStreamInfo( inputParameters, inputStreamInfo,+                &winMmeSpecificInputFlags,+				&throttleProcessingThreadOnOverload,+				&inputDeviceCount );+		if( result != paNoError ) return result;++		inputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * inputDeviceCount );+        if( !inputDevices ) return paInsufficientMemory;++		result = RetrieveDevicesFromStreamParameters( hostApi, inputParameters, inputStreamInfo, inputDevices, inputDeviceCount );+		if( result != paNoError ) return result;++		result = ValidateInputChannelCounts( hostApi, inputDevices, inputDeviceCount );+		if( result != paNoError ) return result;++        hostInputSampleFormat =+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );++        if( inputDeviceCount != 1 ){+            /* always use direct speakers when using multi-device multichannel mode */+            inputChannelMask = PAWIN_SPEAKER_DIRECTOUT;           +        }+        else+        {+            if( inputStreamInfo && inputStreamInfo->flags & paWinMmeUseChannelMask )+                inputChannelMask = inputStreamInfo->channelMask;+            else+                inputChannelMask = PaWin_DefaultChannelMask( inputDevices[0].channelCount );+        }+	}+    else+    {+        inputChannelCount = 0;+        inputSampleFormat = 0;+        suggestedInputLatency = 0.;+        inputStreamInfo = 0;+        hostInputSampleFormat = 0;+    }+++    if( outputParameters )+    {+        outputChannelCount = outputParameters->channelCount;+        outputSampleFormat = outputParameters->sampleFormat;+        suggestedOutputLatency = outputParameters->suggestedLatency;++        outputDeviceCount = 1;++		/* validate output hostApiSpecificStreamInfo */+        outputStreamInfo = (PaWinMmeStreamInfo*)outputParameters->hostApiSpecificStreamInfo;+		result = ValidateWinMmeSpecificStreamInfo( outputParameters, outputStreamInfo,+                &winMmeSpecificOutputFlags,+				&throttleProcessingThreadOnOverload,+				&outputDeviceCount );+		if( result != paNoError ) return result;++		outputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * outputDeviceCount );+        if( !outputDevices ) return paInsufficientMemory;++		result = RetrieveDevicesFromStreamParameters( hostApi, outputParameters, outputStreamInfo, outputDevices, outputDeviceCount );+		if( result != paNoError ) return result;++		result = ValidateOutputChannelCounts( hostApi, outputDevices, outputDeviceCount );+		if( result != paNoError ) return result;++        hostOutputSampleFormat =+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );++        if( outputDeviceCount != 1 ){+            /* always use direct speakers when using multi-device multichannel mode */+            outputChannelMask = PAWIN_SPEAKER_DIRECTOUT;           +        }+        else+        {+            if( outputStreamInfo && outputStreamInfo->flags & paWinMmeUseChannelMask )+                outputChannelMask = outputStreamInfo->channelMask;+            else+                outputChannelMask = PaWin_DefaultChannelMask( outputDevices[0].channelCount );+        }+    }+    else+    {+        outputChannelCount = 0;+        outputSampleFormat = 0;+        outputStreamInfo = 0;+        hostOutputSampleFormat = 0;+        suggestedOutputLatency = 0.;+    }+++    /*+        IMPLEMENT ME:+            - alter sampleRate to a close allowable rate if possible / necessary+    */+++    /* validate platform specific flags */+    if( (streamFlags & paPlatformSpecificFlags) != 0 )+        return paInvalidFlag; /* unexpected platform specific flag */+++    /* always disable clipping and dithering if we are outputting a raw spdif stream */+    if( (winMmeSpecificOutputFlags & paWinMmeWaveFormatDolbyAc3Spdif)+            || (winMmeSpecificOutputFlags & paWinMmeWaveFormatWmaSpdif) ){++        streamFlags = streamFlags | paClipOff | paDitherOff;+    }+++    result = CalculateBufferSettings( &framesPerHostInputBuffer, &hostInputBufferCount,+                &framesPerHostOutputBuffer, &hostOutputBufferCount,+                inputChannelCount, hostInputSampleFormat, suggestedInputLatency, inputStreamInfo,+                outputChannelCount, hostOutputSampleFormat, suggestedOutputLatency, outputStreamInfo,+                sampleRate, framesPerBuffer );+    if( result != paNoError ) goto error;+++    stream = (PaWinMmeStream*)PaUtil_AllocateMemory( sizeof(PaWinMmeStream) );+    if( !stream )+    {+        result = paInsufficientMemory;+        goto error;+    }++    InitializeSingleDirectionHandlesAndBuffers( &stream->input );+    InitializeSingleDirectionHandlesAndBuffers( &stream->output );++    stream->abortEvent = 0;+    stream->processingThread = 0;++    stream->throttleProcessingThreadOnOverload = throttleProcessingThreadOnOverload;++    PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,+                                           ( (streamCallback)+                                            ? &winMmeHostApi->callbackStreamInterface+                                            : &winMmeHostApi->blockingStreamInterface ),+                                           streamCallback, userData );+    streamRepresentationIsInitialized = 1;++    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );+++    if( inputParameters && outputParameters ) /* full duplex */+    {+        if( framesPerHostInputBuffer < framesPerHostOutputBuffer )+        {+            assert( (framesPerHostOutputBuffer % framesPerHostInputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */++            framesPerBufferProcessorCall = framesPerHostInputBuffer;+        }+        else+        {+            assert( (framesPerHostInputBuffer % framesPerHostOutputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */+            +            framesPerBufferProcessorCall = framesPerHostOutputBuffer;+        }+    }+    else if( inputParameters )+    {+        framesPerBufferProcessorCall = framesPerHostInputBuffer;+    }+    else if( outputParameters )+    {+        framesPerBufferProcessorCall = framesPerHostOutputBuffer;+    }++    stream->input.framesPerBuffer = framesPerHostInputBuffer;+    stream->output.framesPerBuffer = framesPerHostOutputBuffer;++    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,+                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,+                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,+                    sampleRate, streamFlags, framesPerBuffer,+                    framesPerBufferProcessorCall, paUtilFixedHostBufferSize,+                    streamCallback, userData );+    if( result != paNoError ) goto error;+    +    bufferProcessorIsInitialized = 1;++    /* stream info input latency is the minimum buffering latency (unlike suggested and default which are *maximums*) */+    stream->streamRepresentation.streamInfo.inputLatency =+            (double)(PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)+                + framesPerHostInputBuffer) / sampleRate;+    stream->streamRepresentation.streamInfo.outputLatency =+            (double)(PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)+                + (framesPerHostOutputBuffer * (hostOutputBufferCount-1))) / sampleRate;+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;++    stream->primeStreamUsingCallback = ( (streamFlags&paPrimeOutputBuffersUsingStreamCallback) && streamCallback ) ? 1 : 0;++    /* time to sleep when throttling due to >100% cpu usage.+        -a quater of a buffer's duration */+    stream->throttledSleepMsecs =+            (unsigned long)(stream->bufferProcessor.framesPerHostBuffer *+             stream->bufferProcessor.samplePeriod * .25 * 1000);++    stream->isStopped = 1;+    stream->isActive = 0;+++    /* for maximum compatibility with multi-device multichannel drivers,+        we first open all devices, then we prepare all buffers, finally+        we start all devices ( in StartStream() ). teardown in reverse order.+    */++    if( inputParameters )+    {+        result = InitializeWaveHandles( winMmeHostApi, &stream->input,+                winMmeSpecificInputFlags,+                stream->bufferProcessor.bytesPerHostInputSample, sampleRate,+                inputDevices, inputDeviceCount, inputChannelMask, 1 /* isInput */ );+        if( result != paNoError ) goto error;+    }+    +    if( outputParameters )+    {+        result = InitializeWaveHandles( winMmeHostApi, &stream->output,+                winMmeSpecificOutputFlags,+                stream->bufferProcessor.bytesPerHostOutputSample, sampleRate,+                outputDevices, outputDeviceCount, outputChannelMask, 0 /* isInput */ );+        if( result != paNoError ) goto error;+    }++    if( inputParameters )+    {+        result = InitializeWaveHeaders( &stream->input, hostInputBufferCount,+                hostInputSampleFormat, framesPerHostInputBuffer, inputDevices, 1 /* isInput */ );+        if( result != paNoError ) goto error;+    }++    if( outputParameters )+    {+        result = InitializeWaveHeaders( &stream->output, hostOutputBufferCount,+                hostOutputSampleFormat, framesPerHostOutputBuffer, outputDevices, 0 /* not isInput */ );+        if( result != paNoError ) goto error;++        stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostOutputBuffer * stream->output.bufferCount) / sampleRate);+    }+    else+    {+        stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostInputBuffer * stream->input.bufferCount) / sampleRate);+    }++    +    if( streamCallback )+    {+        /* abort event is only needed for callback streams */+        result = CreateEventWithPaError( &stream->abortEvent, NULL, TRUE, FALSE, NULL );+        if( result != paNoError ) goto error;+    }++    *s = (PaStream*)stream;++    return result;++error:++    if( stream )+    {+        if( stream->abortEvent )+            CloseHandle( stream->abortEvent );+            +        TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );+        TerminateWaveHeaders( &stream->input, 1 /* isInput */ );++        TerminateWaveHandles( &stream->output, 0 /* not isInput */, 1 /* currentlyProcessingAnError */ );+        TerminateWaveHandles( &stream->input, 1 /* isInput */, 1 /* currentlyProcessingAnError */ );++        if( bufferProcessorIsInitialized )+            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );++        if( streamRepresentationIsInitialized )+            PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );++        PaUtil_FreeMemory( stream );+    }++    return result;+}+++/* return non-zero if all current buffers are done */+static int BuffersAreDone( WAVEHDR **waveHeaders, unsigned int deviceCount, int bufferIndex )+{+    unsigned int i;+    +    for( i=0; i < deviceCount; ++i )+    {+        if( !(waveHeaders[i][ bufferIndex ].dwFlags & WHDR_DONE) )+        {+            return 0;+        }         +    }++    return 1;+}++static int CurrentInputBuffersAreDone( PaWinMmeStream *stream )+{+    return BuffersAreDone( stream->input.waveHeaders, stream->input.deviceCount, stream->input.currentBufferIndex );+}++static int CurrentOutputBuffersAreDone( PaWinMmeStream *stream )+{+    return BuffersAreDone( stream->output.waveHeaders, stream->output.deviceCount, stream->output.currentBufferIndex );+}+++/* return non-zero if any buffers are queued */+static int NoBuffersAreQueued( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )+{+    unsigned int i, j;++    if( handlesAndBuffers->waveHandles )+    {+        for( i=0; i < handlesAndBuffers->bufferCount; ++i )+        {+            for( j=0; j < handlesAndBuffers->deviceCount; ++j )+            {+                if( !( handlesAndBuffers->waveHeaders[ j ][ i ].dwFlags & WHDR_DONE) )+                {+                    return 0;+                }+            }+        }+    }++    return 1;+}+++#define PA_CIRCULAR_INCREMENT_( current, max )\+    ( (((current) + 1) >= (max)) ? (0) : (current+1) )++#define PA_CIRCULAR_DECREMENT_( current, max )\+    ( ((current) == 0) ? ((max)-1) : (current-1) )+    ++static signed long GetAvailableFrames( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )+{+    signed long result = 0;+    unsigned int i;+    +    if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, handlesAndBuffers->currentBufferIndex ) )+    {+        /* we could calculate the following in O(1) if we kept track of the+            last done buffer */+        result = handlesAndBuffers->framesPerBuffer - handlesAndBuffers->framesUsedInCurrentBuffer;++        i = PA_CIRCULAR_INCREMENT_( handlesAndBuffers->currentBufferIndex, handlesAndBuffers->bufferCount );+        while( i != handlesAndBuffers->currentBufferIndex )+        {+            if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, i ) )+            {+                result += handlesAndBuffers->framesPerBuffer;+                i = PA_CIRCULAR_INCREMENT_( i, handlesAndBuffers->bufferCount );+            }+            else+                break;+        }+    }++    return result;+}+++static PaError AdvanceToNextInputBuffer( PaWinMmeStream *stream )+{+    PaError result = paNoError;+    MMRESULT mmresult;+    unsigned int i;++    for( i=0; i < stream->input.deviceCount; ++i )+    {+        stream->input.waveHeaders[i][ stream->input.currentBufferIndex ].dwFlags &= ~WHDR_DONE;+        mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[i],+                                    &stream->input.waveHeaders[i][ stream->input.currentBufferIndex ],+                                    sizeof(WAVEHDR) );+        if( mmresult != MMSYSERR_NOERROR )+        {+            result = paUnanticipatedHostError;+            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+        }+    }++    stream->input.currentBufferIndex =+            PA_CIRCULAR_INCREMENT_( stream->input.currentBufferIndex, stream->input.bufferCount );++    stream->input.framesUsedInCurrentBuffer = 0;++    return result;+}+++static PaError AdvanceToNextOutputBuffer( PaWinMmeStream *stream )+{+    PaError result = paNoError;+    MMRESULT mmresult;+    unsigned int i;++    for( i=0; i < stream->output.deviceCount; ++i )+    {+        mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[i],+                                 &stream->output.waveHeaders[i][ stream->output.currentBufferIndex ],+                                 sizeof(WAVEHDR) );+        if( mmresult != MMSYSERR_NOERROR )+        {+            result = paUnanticipatedHostError;+            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+        }+    }++    stream->output.currentBufferIndex =+            PA_CIRCULAR_INCREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );++    stream->output.framesUsedInCurrentBuffer = 0;+    +    return result;+}+++/* requeue all but the most recent input with the driver. Used for catching+    up after a total input buffer underrun */+static PaError CatchUpInputBuffers( PaWinMmeStream *stream )+{+    PaError result = paNoError;+    unsigned int i;+    +    for( i=0; i < stream->input.bufferCount - 1; ++i )+    {+        result = AdvanceToNextInputBuffer( stream );+        if( result != paNoError )+            break;+    }++    return result;+}+++/* take the most recent output and duplicate it to all other output buffers+    and requeue them. Used for catching up after a total output buffer underrun.+*/+static PaError CatchUpOutputBuffers( PaWinMmeStream *stream )+{+    PaError result = paNoError;+    unsigned int i, j;+    unsigned int previousBufferIndex =+            PA_CIRCULAR_DECREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );++    for( i=0; i < stream->output.bufferCount - 1; ++i )+    {+        for( j=0; j < stream->output.deviceCount; ++j )+        {+            if( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData+                    != stream->output.waveHeaders[j][ previousBufferIndex ].lpData )+            {+                CopyMemory( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData,+                            stream->output.waveHeaders[j][ previousBufferIndex ].lpData,+                            stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].dwBufferLength );+            }+        }++        result = AdvanceToNextOutputBuffer( stream );+        if( result != paNoError )+            break;+    }++    return result;+}+++PA_THREAD_FUNC ProcessingThreadProc( void *pArg )+{+    PaWinMmeStream *stream = (PaWinMmeStream *)pArg;+    HANDLE events[3];+    int eventCount = 0;+    DWORD result = paNoError;+    DWORD waitResult;+    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);+    int hostBuffersAvailable;+    signed int hostInputBufferIndex, hostOutputBufferIndex;+    PaStreamCallbackFlags statusFlags;+    int callbackResult;+    int done = 0;+    unsigned int channel, i;+    unsigned long framesProcessed;+    +    /* prepare event array for call to WaitForMultipleObjects() */+    if( stream->input.bufferEvent )+        events[eventCount++] = stream->input.bufferEvent;+    if( stream->output.bufferEvent )+        events[eventCount++] = stream->output.bufferEvent;+    events[eventCount++] = stream->abortEvent;++    statusFlags = 0; /** @todo support paInputUnderflow, paOutputOverflow and paNeverDropInput */+    +    /* loop until something causes us to stop */+    do{+        /* wait for MME to signal that a buffer is available, or for+            the PA abort event to be signaled.++          When this indicates that one or more buffers are available+          NoBuffersAreQueued() and Current*BuffersAreDone are used below to+          poll for additional done buffers. NoBuffersAreQueued() will fail+          to identify an underrun/overflow if the driver doesn't mark all done+          buffers prior to signalling the event. Some drivers do this+          (eg RME Digi96, and others don't eg VIA PC 97 input). This isn't a+          huge problem, it just means that we won't always be able to detect+          underflow/overflow.+        */+        waitResult = WaitForMultipleObjects( eventCount, events, FALSE /* wait all = FALSE */, timeout );+        if( waitResult == WAIT_FAILED )+        {+            result = paUnanticipatedHostError;+            /** @todo FIXME/REVIEW: can't return host error info from an asyncronous thread. see http://www.portaudio.com/trac/ticket/143 */+            done = 1;+        }+        else if( waitResult == WAIT_TIMEOUT )+        {+            /* if a timeout is encountered, continue */+        }++        if( stream->abortProcessing )+        {+            /* Pa_AbortStream() has been called, stop processing immediately */+            done = 1;+        }+        else if( stream->stopProcessing )+        {+            /* Pa_StopStream() has been called or the user callback returned+                non-zero, processing will continue until all output buffers+                are marked as done. The stream will stop immediately if it+                is input-only.+            */++            if( PA_IS_OUTPUT_STREAM_(stream) )+            {+                if( NoBuffersAreQueued( &stream->output ) )+                    done = 1; /* Will cause thread to return. */+            }+            else+            {+                /* input only stream */+                done = 1; /* Will cause thread to return. */+            }+        }+        else+        {+            hostBuffersAvailable = 1;++            /* process all available host buffers */+            do+            {+                hostInputBufferIndex = -1;+                hostOutputBufferIndex = -1;+                +                if( PA_IS_INPUT_STREAM_(stream) )+                {+                    if( CurrentInputBuffersAreDone( stream ) )+                    {+                        if( NoBuffersAreQueued( &stream->input ) )+                        {+                            /** @todo+                               if all of the other buffers are also ready then+                               we discard all but the most recent. This is an+                               input buffer overflow. FIXME: these buffers should+                               be passed to the callback in a paNeverDropInput+                               stream. http://www.portaudio.com/trac/ticket/142++                               note that it is also possible for an input overflow+                               to happen while the callback is processing a buffer.+                               that is handled further down.+                            */+                            result = CatchUpInputBuffers( stream );+                            if( result != paNoError )+                                done = 1;++                            statusFlags |= paInputOverflow;+                        }++                        hostInputBufferIndex = stream->input.currentBufferIndex;+                    }+                }++                if( PA_IS_OUTPUT_STREAM_(stream) )+                {+                    if( CurrentOutputBuffersAreDone( stream ) )+                    {+                        /* ok, we have an output buffer */+                        +                        if( NoBuffersAreQueued( &stream->output ) )+                        {+                            /*+                            if all of the other buffers are also ready, catch up by copying+                            the most recently generated buffer into all but one of the output+                            buffers.++                            note that this catch up code only handles the case where all+                            buffers have been played out due to this thread not having+                            woken up at all. a more common case occurs when this thread+                            is woken up, processes one buffer, but takes too long, and as+                            a result all the other buffers have become un-queued. that+                            case is handled further down.+                            */++                            result = CatchUpOutputBuffers( stream );+                            if( result != paNoError )+                                done = 1;++                            statusFlags |= paOutputUnderflow;+                        }++                        hostOutputBufferIndex = stream->output.currentBufferIndex;+                    }+                }++               +                if( (PA_IS_FULL_DUPLEX_STREAM_(stream) && hostInputBufferIndex != -1 && hostOutputBufferIndex != -1) ||+                        (PA_IS_HALF_DUPLEX_STREAM_(stream) && ( hostInputBufferIndex != -1 || hostOutputBufferIndex != -1 ) ) )+                {+                    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */+++                    if( PA_IS_OUTPUT_STREAM_(stream) )+                    {+                        /* set timeInfo.currentTime and calculate timeInfo.outputBufferDacTime+                            from the current wave out position */+                        MMTIME mmtime;+                        double timeBeforeGetPosition, timeAfterGetPosition;+                        double time;+                        long framesInBufferRing; 		+                        long writePosition;+                        long playbackPosition;+                        HWAVEOUT firstWaveOutDevice = ((HWAVEOUT*)stream->output.waveHandles)[0];+                        +                        mmtime.wType = TIME_SAMPLES;+                        timeBeforeGetPosition = PaUtil_GetTime();+                        waveOutGetPosition( firstWaveOutDevice, &mmtime, sizeof(MMTIME) );+                        timeAfterGetPosition = PaUtil_GetTime();++                        timeInfo.currentTime = timeAfterGetPosition;++                        /* approximate time at which wave out position was measured+                            as half way between timeBeforeGetPosition and timeAfterGetPosition */+                        time = timeBeforeGetPosition + (timeAfterGetPosition - timeBeforeGetPosition) * .5;+                        +                        framesInBufferRing = stream->output.bufferCount * stream->bufferProcessor.framesPerHostBuffer;+                        playbackPosition = mmtime.u.sample % framesInBufferRing;++                        writePosition = stream->output.currentBufferIndex * stream->bufferProcessor.framesPerHostBuffer+                                + stream->output.framesUsedInCurrentBuffer;+                       +                        if( playbackPosition >= writePosition ){+                            timeInfo.outputBufferDacTime =+                                    time + ((double)( writePosition + (framesInBufferRing - playbackPosition) ) * stream->bufferProcessor.samplePeriod );+                        }else{+                            timeInfo.outputBufferDacTime =+                                    time + ((double)( writePosition - playbackPosition ) * stream->bufferProcessor.samplePeriod );+                        }+                    }+++                    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );++                    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, statusFlags  );++                    /* reset status flags once they have been passed to the buffer processor */+                    statusFlags = 0;++                    if( PA_IS_INPUT_STREAM_(stream) )+                    {+                        PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );++                        channel = 0;+                        for( i=0; i<stream->input.deviceCount; ++i )+                        {+                             /* we have stored the number of channels in the buffer in dwUser */+                            int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;+                            +                            PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,+                                    stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData ++                                        stream->input.framesUsedInCurrentBuffer * channelCount *+                                        stream->bufferProcessor.bytesPerHostInputSample,+                                    channelCount );+                                    ++                            channel += channelCount;+                        }+                    }++                    if( PA_IS_OUTPUT_STREAM_(stream) )+                    {+                        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );+                        +                        channel = 0;+                        for( i=0; i<stream->output.deviceCount; ++i )+                        {+                            /* we have stored the number of channels in the buffer in dwUser */+                            int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;++                            PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,+                                    stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData ++                                        stream->output.framesUsedInCurrentBuffer * channelCount *+                                        stream->bufferProcessor.bytesPerHostOutputSample,+                                    channelCount );++                            channel += channelCount;+                        }+                    }++                    callbackResult = paContinue;+                    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );++                    stream->input.framesUsedInCurrentBuffer += framesProcessed;+                    stream->output.framesUsedInCurrentBuffer += framesProcessed;++                    PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );++                    if( callbackResult == paContinue )+                    {+                        /* nothing special to do */+                    }+                    else if( callbackResult == paAbort )+                    {+                        stream->abortProcessing = 1;+                        done = 1;+                        /** @todo FIXME: should probably reset the output device immediately once the callback returns paAbort +                            see: http://www.portaudio.com/trac/ticket/141+                        */+                        result = paNoError;+                    }+                    else+                    {+                        /* User callback has asked us to stop with paComplete or other non-zero value */+                        stream->stopProcessing = 1; /* stop once currently queued audio has finished */+                        result = paNoError;+                    }+++                    if( PA_IS_INPUT_STREAM_(stream)+                            && stream->stopProcessing == 0 && stream->abortProcessing == 0+                            && stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )+                    {+                        if( NoBuffersAreQueued( &stream->input ) )+                        {+                            /** @todo need to handle PaNeverDropInput here where necessary */+                            result = CatchUpInputBuffers( stream );+                            if( result != paNoError )+                                done = 1;++                            statusFlags |= paInputOverflow;+                        }++                        result = AdvanceToNextInputBuffer( stream );+                        if( result != paNoError )+                            done = 1;+                    }++                    +                    if( PA_IS_OUTPUT_STREAM_(stream) && !stream->abortProcessing )+                    {+                        if( stream->stopProcessing &&+                                stream->output.framesUsedInCurrentBuffer < stream->output.framesPerBuffer )+                        {+                            /* zero remaining samples in output output buffer and flush */++                            stream->output.framesUsedInCurrentBuffer += PaUtil_ZeroOutput( &stream->bufferProcessor,+                                    stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );++                            /* we send the entire buffer to the output devices, but we could+                                just send a partial buffer, rather than zeroing the unused+                                samples.+                            */+                        }++                        if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )+                        {+                            /* check for underflow before enquing the just-generated buffer,+                                but recover from underflow after enquing it. This ensures+                                that the most recent audio segment is repeated */+                            int outputUnderflow = NoBuffersAreQueued( &stream->output );++                            result = AdvanceToNextOutputBuffer( stream );+                            if( result != paNoError )+                                done = 1;++                            if( outputUnderflow && !done && !stream->stopProcessing )+                            {+                                /* Recover from underflow in the case where the+                                    underflow occured while processing the buffer+                                    we just finished */++                                result = CatchUpOutputBuffers( stream );+                                if( result != paNoError )+                                    done = 1;++                                statusFlags |= paOutputUnderflow;+                            }+                        }+                    }+                    +                    if( stream->throttleProcessingThreadOnOverload != 0 )+                    {+                        if( stream->stopProcessing || stream->abortProcessing )+                        {+                            if( stream->processingThreadPriority != stream->highThreadPriority )+                            {+                                SetThreadPriority( stream->processingThread, stream->highThreadPriority );+                                stream->processingThreadPriority = stream->highThreadPriority;+                            }+                        }+                        else if( PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) > 1. )+                        {+                            if( stream->processingThreadPriority != stream->throttledThreadPriority )+                            {+                                SetThreadPriority( stream->processingThread, stream->throttledThreadPriority );+                                stream->processingThreadPriority = stream->throttledThreadPriority;+                            }++                            /* sleep to give other processes a go */+                            Sleep( stream->throttledSleepMsecs );+                        }+                        else+                        {+                            if( stream->processingThreadPriority != stream->highThreadPriority )+                            {+                                SetThreadPriority( stream->processingThread, stream->highThreadPriority );+                                stream->processingThreadPriority = stream->highThreadPriority;+                            }+                        }+                    }+                }+                else+                {+                    hostBuffersAvailable = 0;+                }+            }+            while( hostBuffersAvailable &&+                    stream->stopProcessing == 0 &&+                    stream->abortProcessing == 0 &&+                    !done );+        }+    }+    while( !done );++    stream->isActive = 0;++    if( stream->streamRepresentation.streamFinishedCallback != 0 )+        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );++    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );+    +    return result;+}+++/*+    When CloseStream() is called, the multi-api layer ensures that+    the stream has already been stopped or aborted.+*/+static PaError CloseStream( PaStream* s )+{+    PaError result;+    PaWinMmeStream *stream = (PaWinMmeStream*)s;++    result = CloseHandleWithPaError( stream->abortEvent );+    if( result != paNoError ) goto error;+    +    TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );+    TerminateWaveHeaders( &stream->input, 1 /* isInput */ );++    TerminateWaveHandles( &stream->output, 0 /* not isInput */, 0 /* not currentlyProcessingAnError */ );+    TerminateWaveHandles( &stream->input, 1 /* isInput */, 0 /* not currentlyProcessingAnError */ );+    +    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );+    PaUtil_FreeMemory( stream );++error:+    /** @todo REVIEW: what is the best way to clean up a stream if an error is detected? */+    return result;+}+++static PaError StartStream( PaStream *s )+{+    PaError result;+    PaWinMmeStream *stream = (PaWinMmeStream*)s;+    MMRESULT mmresult;+    unsigned int i, j;+    int callbackResult;+	unsigned int channel;+ 	unsigned long framesProcessed;+	PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement this for stream priming */+    +    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );+    +    if( PA_IS_INPUT_STREAM_(stream) )+    {+        for( i=0; i<stream->input.bufferCount; ++i )+        {+            for( j=0; j<stream->input.deviceCount; ++j )+            {+                stream->input.waveHeaders[j][i].dwFlags &= ~WHDR_DONE;+                mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[j], &stream->input.waveHeaders[j][i], sizeof(WAVEHDR) );+                if( mmresult != MMSYSERR_NOERROR )+                {+                    result = paUnanticipatedHostError;+                    PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+                    goto error;+                }+            }+        }+        stream->input.currentBufferIndex = 0;+        stream->input.framesUsedInCurrentBuffer = 0;+    }++    if( PA_IS_OUTPUT_STREAM_(stream) )+    {+        for( i=0; i<stream->output.deviceCount; ++i )+        {+            if( (mmresult = waveOutPause( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )+            {+                result = paUnanticipatedHostError;+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+                goto error;+            }+        }++        for( i=0; i<stream->output.bufferCount; ++i )+        {+            if( stream->primeStreamUsingCallback )+            {++                stream->output.framesUsedInCurrentBuffer = 0;+                do{++                    PaUtil_BeginBufferProcessing( &stream->bufferProcessor,+                            &timeInfo,+                            paPrimingOutput | ((stream->input.bufferCount > 0 ) ? paInputUnderflow : 0));++                    if( stream->input.bufferCount > 0 )+                        PaUtil_SetNoInput( &stream->bufferProcessor );++                    PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );++                    channel = 0;+                    for( j=0; j<stream->output.deviceCount; ++j )+                    {+                        /* we have stored the number of channels in the buffer in dwUser */+                        int channelCount = (int)stream->output.waveHeaders[j][i].dwUser;++                        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,+                                stream->output.waveHeaders[j][i].lpData ++                                stream->output.framesUsedInCurrentBuffer * channelCount *+                                stream->bufferProcessor.bytesPerHostOutputSample,+                                channelCount );++                        /* we have stored the number of channels in the buffer in dwUser */+                        channel += channelCount;+                    }++                    callbackResult = paContinue;+                    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );+                    stream->output.framesUsedInCurrentBuffer += framesProcessed;++                    if( callbackResult != paContinue )+                    {+                        /** @todo fix this, what do we do if callback result is non-zero during stream+                            priming?++                            for complete: play out primed waveHeaders as usual+                            for abort: clean up immediately.+                       */+                    }++                }while( stream->output.framesUsedInCurrentBuffer != stream->output.framesPerBuffer );++            }+            else+            {+                for( j=0; j<stream->output.deviceCount; ++j )+                {+                    ZeroMemory( stream->output.waveHeaders[j][i].lpData, stream->output.waveHeaders[j][i].dwBufferLength );+                }+            }   ++            /* we queue all channels of a single buffer frame (accross all+                devices, because some multidevice multichannel drivers work+                better this way */+            for( j=0; j<stream->output.deviceCount; ++j )+            {+                mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[j], &stream->output.waveHeaders[j][i], sizeof(WAVEHDR) );+                if( mmresult != MMSYSERR_NOERROR )+                {+                    result = paUnanticipatedHostError;+                    PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+                    goto error;+                }+            }+        }+        stream->output.currentBufferIndex = 0;+        stream->output.framesUsedInCurrentBuffer = 0;+    }+++    stream->isStopped = 0;+    stream->isActive = 1;+    stream->stopProcessing = 0;+    stream->abortProcessing = 0;++    result = ResetEventWithPaError( stream->input.bufferEvent );+    if( result != paNoError ) goto error;++    result = ResetEventWithPaError( stream->output.bufferEvent );+    if( result != paNoError ) goto error;+    +    +    if( stream->streamRepresentation.streamCallback )+    {+        /* callback stream */++        result = ResetEventWithPaError( stream->abortEvent );+        if( result != paNoError ) goto error;++        /* Create thread that waits for audio buffers to be ready for processing. */+        stream->processingThread = CREATE_THREAD;+        if( !stream->processingThread )+        {+            result = paUnanticipatedHostError;+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );+            goto error;+        }++        /** @todo could have mme specific stream parameters to allow the user+            to set the callback thread priorities */+        stream->highThreadPriority = THREAD_PRIORITY_TIME_CRITICAL;+        stream->throttledThreadPriority = THREAD_PRIORITY_NORMAL;++        if( !SetThreadPriority( stream->processingThread, stream->highThreadPriority ) )+        {+            result = paUnanticipatedHostError;+            PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );+            goto error;+        }+        stream->processingThreadPriority = stream->highThreadPriority;+    }+    else+    {+        /* blocking read/write stream */++    }++    if( PA_IS_INPUT_STREAM_(stream) )+    {+        for( i=0; i < stream->input.deviceCount; ++i )+        {+            mmresult = waveInStart( ((HWAVEIN*)stream->input.waveHandles)[i] );+            PA_DEBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult));+            if( mmresult != MMSYSERR_NOERROR )+            {+                result = paUnanticipatedHostError;+                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+                goto error;+            }+        }+    }++    if( PA_IS_OUTPUT_STREAM_(stream) )+    {+        for( i=0; i < stream->output.deviceCount; ++i )+        {+            if( (mmresult = waveOutRestart( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )+            {+                result = paUnanticipatedHostError;+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+                goto error;+            }+        }+    }++    return result;++error:+    /** @todo FIXME: implement recovery as best we can+    This should involve rolling back to a state as-if this function had never been called+    */+    return result;+}+++static PaError StopStream( PaStream *s )+{+    PaError result = paNoError;+    PaWinMmeStream *stream = (PaWinMmeStream*)s;+    int timeout;+    DWORD waitResult;+    MMRESULT mmresult;+    signed int hostOutputBufferIndex;+    unsigned int channel, waitCount, i;                  +    +    /** @todo+        REVIEW: the error checking in this function needs review. the basic+        idea is to return from this function in a known state - for example+        there is no point avoiding calling waveInReset just because+        the thread times out.+    */++    if( stream->processingThread )+    {+        /* callback stream */++        /* Tell processing thread to stop generating more data and to let current data play out. */+        stream->stopProcessing = 1;++        /* Calculate timeOut longer than longest time it could take to return all buffers. */+        timeout = (int)(stream->allBuffersDurationMs * 1.5);+        if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )+            timeout = PA_MME_MIN_TIMEOUT_MSEC_;++        PA_DEBUG(("WinMME StopStream: waiting for background thread.\n"));++        waitResult = WaitForSingleObject( stream->processingThread, timeout );+        if( waitResult == WAIT_TIMEOUT )+        {+            /* try to abort */+            stream->abortProcessing = 1;+            SetEvent( stream->abortEvent );+            waitResult = WaitForSingleObject( stream->processingThread, timeout );+            if( waitResult == WAIT_TIMEOUT )+            {+                PA_DEBUG(("WinMME StopStream: timed out while waiting for background thread to finish.\n"));+                result = paTimedOut;+            }+        }++        CloseHandle( stream->processingThread );+        stream->processingThread = NULL;+    }+    else+    {+        /* blocking read / write stream */++        if( PA_IS_OUTPUT_STREAM_(stream) )+        {+            if( stream->output.framesUsedInCurrentBuffer > 0 )+            {+                /* there are still unqueued frames in the current buffer, so flush them */++                hostOutputBufferIndex = stream->output.currentBufferIndex;++                PaUtil_SetOutputFrameCount( &stream->bufferProcessor,+                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );+                +                channel = 0;+                for( i=0; i<stream->output.deviceCount; ++i )+                {+                    /* we have stored the number of channels in the buffer in dwUser */+                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;++                    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,+                            stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData ++                                stream->output.framesUsedInCurrentBuffer * channelCount *+                                stream->bufferProcessor.bytesPerHostOutputSample,+                            channelCount );++                    channel += channelCount;+                }++                PaUtil_ZeroOutput( &stream->bufferProcessor,+                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );++                /* we send the entire buffer to the output devices, but we could+                    just send a partial buffer, rather than zeroing the unused+                    samples.+                */+                AdvanceToNextOutputBuffer( stream );+            }+            ++            timeout = (stream->allBuffersDurationMs / stream->output.bufferCount) + 1;+            if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )+                timeout = PA_MME_MIN_TIMEOUT_MSEC_;++            waitCount = 0;+            while( !NoBuffersAreQueued( &stream->output ) && waitCount <= stream->output.bufferCount )+            {+                /* wait for MME to signal that a buffer is available */+                waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );+                if( waitResult == WAIT_FAILED )+                {+                    break;+                }+                else if( waitResult == WAIT_TIMEOUT )+                {+                    /* keep waiting */+                }++                ++waitCount;+            }+        }+    }++    if( PA_IS_OUTPUT_STREAM_(stream) )+    {+        for( i =0; i < stream->output.deviceCount; ++i )+        {+            mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );+            if( mmresult != MMSYSERR_NOERROR )+            {+                result = paUnanticipatedHostError;+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+            }+        }+    }++    if( PA_IS_INPUT_STREAM_(stream) )+    {+        for( i=0; i < stream->input.deviceCount; ++i )+        {+            mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );+            if( mmresult != MMSYSERR_NOERROR )+            {+                result = paUnanticipatedHostError;+                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+            }+        }+    }++    stream->isStopped = 1;+    stream->isActive = 0;++    return result;+}+++static PaError AbortStream( PaStream *s )+{+    PaError result = paNoError;+    PaWinMmeStream *stream = (PaWinMmeStream*)s;+    int timeout;+    DWORD waitResult;+    MMRESULT mmresult;+    unsigned int i;+    +    /** @todo+        REVIEW: the error checking in this function needs review. the basic+        idea is to return from this function in a known state - for example+        there is no point avoiding calling waveInReset just because+        the thread times out.+    */++    if( stream->processingThread )+    {+        /* callback stream */+        +        /* Tell processing thread to abort immediately */+        stream->abortProcessing = 1;+        SetEvent( stream->abortEvent );+    }+++    if( PA_IS_OUTPUT_STREAM_(stream) )+    {+        for( i =0; i < stream->output.deviceCount; ++i )+        {+            mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );+            if( mmresult != MMSYSERR_NOERROR )+            {+                PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );+                return paUnanticipatedHostError;+            }+        }+    }++    if( PA_IS_INPUT_STREAM_(stream) )+    {+        for( i=0; i < stream->input.deviceCount; ++i )+        {+            mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );+            if( mmresult != MMSYSERR_NOERROR )+            {+                PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );+                return paUnanticipatedHostError;+            }+        }+    }+++    if( stream->processingThread )+    {+        /* callback stream */+        +        PA_DEBUG(("WinMME AbortStream: waiting for background thread.\n"));++        /* Calculate timeOut longer than longest time it could take to return all buffers. */+        timeout = (int)(stream->allBuffersDurationMs * 1.5);+        if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )+            timeout = PA_MME_MIN_TIMEOUT_MSEC_;+            +        waitResult = WaitForSingleObject( stream->processingThread, timeout );+        if( waitResult == WAIT_TIMEOUT )+        {+            PA_DEBUG(("WinMME AbortStream: timed out while waiting for background thread to finish.\n"));+            return paTimedOut;+        }++        CloseHandle( stream->processingThread );+        stream->processingThread = NULL;+    }++    stream->isStopped = 1;+    stream->isActive = 0;++    return result;+}+++static PaError IsStreamStopped( PaStream *s )+{+    PaWinMmeStream *stream = (PaWinMmeStream*)s;++    return stream->isStopped;+}+++static PaError IsStreamActive( PaStream *s )+{+    PaWinMmeStream *stream = (PaWinMmeStream*)s;++    return stream->isActive;+}+++static PaTime GetStreamTime( PaStream *s )+{+    (void) s; /* unused parameter */+    +    return PaUtil_GetTime();+}+++static double GetStreamCpuLoad( PaStream* s )+{+    PaWinMmeStream *stream = (PaWinMmeStream*)s;++    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );+}+++/*+    As separate stream interfaces are used for blocking and callback+    streams, the following functions can be guaranteed to only be called+    for blocking streams.+*/++static PaError ReadStream( PaStream* s,+                           void *buffer,+                           unsigned long frames )+{+    PaError result = paNoError;+    PaWinMmeStream *stream = (PaWinMmeStream*)s;+    void *userBuffer;+    unsigned long framesRead = 0;+    unsigned long framesProcessed;+    signed int hostInputBufferIndex;+    DWORD waitResult;+    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);+    unsigned int channel, i;+    +    if( PA_IS_INPUT_STREAM_(stream) )+    {+        /* make a local copy of the user buffer pointer(s). this is necessary+            because PaUtil_CopyInput() advances these pointers every time+            it is called.+        */+        if( stream->bufferProcessor.userInputIsInterleaved )+        {+            userBuffer = buffer;+        }+        else+        {+            userBuffer = (void*)alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount );+            if( !userBuffer )+                return paInsufficientMemory;+            for( i = 0; i<stream->bufferProcessor.inputChannelCount; ++i )+                ((void**)userBuffer)[i] = ((void**)buffer)[i];+        }+        +        do{+            if( CurrentInputBuffersAreDone( stream ) )+            {+                if( NoBuffersAreQueued( &stream->input ) )+                {+                    /** @todo REVIEW: consider what to do if the input overflows.+                        do we requeue all of the buffers? should we be running+                        a thread to make sure they are always queued? +                        see: http://www.portaudio.com/trac/ticket/117+                        */++                    result = paInputOverflowed;+                }++                hostInputBufferIndex = stream->input.currentBufferIndex;++                PaUtil_SetInputFrameCount( &stream->bufferProcessor,+                        stream->input.framesPerBuffer - stream->input.framesUsedInCurrentBuffer );+                +                channel = 0;+                for( i=0; i<stream->input.deviceCount; ++i )+                {+                    /* we have stored the number of channels in the buffer in dwUser */+                    int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;++                    PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,+                            stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData ++                                stream->input.framesUsedInCurrentBuffer * channelCount *+                                stream->bufferProcessor.bytesPerHostInputSample,+                            channelCount );++                    channel += channelCount;+                }+                +                framesProcessed = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, frames - framesRead );++                stream->input.framesUsedInCurrentBuffer += framesProcessed;+                if( stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )+                {+                    result = AdvanceToNextInputBuffer( stream );+                    if( result != paNoError )+                        break;+                }++                framesRead += framesProcessed;      ++            }else{+                /* wait for MME to signal that a buffer is available */+                waitResult = WaitForSingleObject( stream->input.bufferEvent, timeout );+                if( waitResult == WAIT_FAILED )+                {+                    result = paUnanticipatedHostError;+                    break;+                }+                else if( waitResult == WAIT_TIMEOUT )+                {+                    /* if a timeout is encountered, continue,+                        perhaps we should give up eventually+                    */+                }         +            }+        }while( framesRead < frames );+    }+    else+    {+        result = paCanNotReadFromAnOutputOnlyStream;+    }++    return result;+}+++static PaError WriteStream( PaStream* s,+                            const void *buffer,+                            unsigned long frames )+{+    PaError result = paNoError;+    PaWinMmeStream *stream = (PaWinMmeStream*)s;+    const void *userBuffer;+    unsigned long framesWritten = 0;+    unsigned long framesProcessed;+    signed int hostOutputBufferIndex;+    DWORD waitResult;+    DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);+    unsigned int channel, i;++        +    if( PA_IS_OUTPUT_STREAM_(stream) )+    {+        /* make a local copy of the user buffer pointer(s). this is necessary+            because PaUtil_CopyOutput() advances these pointers every time+            it is called.+        */+        if( stream->bufferProcessor.userOutputIsInterleaved )+        {+            userBuffer = buffer;+        }+        else+        {+            userBuffer = (const void*)alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount );+            if( !userBuffer )+                return paInsufficientMemory;+            for( i = 0; i<stream->bufferProcessor.outputChannelCount; ++i )+                ((const void**)userBuffer)[i] = ((const void**)buffer)[i];+        }++        do{+            if( CurrentOutputBuffersAreDone( stream ) )+            {+                if( NoBuffersAreQueued( &stream->output ) )+                {+                    /** @todo REVIEW: consider what to do if the output+                    underflows. do we requeue all the existing buffers with+                    zeros? should we run a separate thread to keep the buffers+                    enqueued at all times? +                    see: http://www.portaudio.com/trac/ticket/117+                    */++                    result = paOutputUnderflowed;+                }++                hostOutputBufferIndex = stream->output.currentBufferIndex;++                PaUtil_SetOutputFrameCount( &stream->bufferProcessor,+                        stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );+                +                channel = 0;+                for( i=0; i<stream->output.deviceCount; ++i )+                {+                    /* we have stored the number of channels in the buffer in dwUser */+                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;++                    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,+                            stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData ++                                stream->output.framesUsedInCurrentBuffer * channelCount *+                                stream->bufferProcessor.bytesPerHostOutputSample,+                            channelCount );++                    channel += channelCount;+                }+                +                framesProcessed = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames - framesWritten );++                stream->output.framesUsedInCurrentBuffer += framesProcessed;+                if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )+                {+                    result = AdvanceToNextOutputBuffer( stream );+                    if( result != paNoError )+                        break;+                }++                framesWritten += framesProcessed;+            }+            else+            {+                /* wait for MME to signal that a buffer is available */+                waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );+                if( waitResult == WAIT_FAILED )+                {+                    result = paUnanticipatedHostError;+                    break;+                }+                else if( waitResult == WAIT_TIMEOUT )+                {+                    /* if a timeout is encountered, continue,+                        perhaps we should give up eventually+                    */+                }             +            }        +        }while( framesWritten < frames );+    }+    else+    {+        result = paCanNotWriteToAnInputOnlyStream;+    }+    +    return result;+}+++static signed long GetStreamReadAvailable( PaStream* s )+{+    PaWinMmeStream *stream = (PaWinMmeStream*)s;+    +    if( PA_IS_INPUT_STREAM_(stream) )+        return GetAvailableFrames( &stream->input );+    else+        return paCanNotReadFromAnOutputOnlyStream;+}+++static signed long GetStreamWriteAvailable( PaStream* s )+{+    PaWinMmeStream *stream = (PaWinMmeStream*)s;+    +    if( PA_IS_OUTPUT_STREAM_(stream) )+        return GetAvailableFrames( &stream->output );+    else+        return paCanNotWriteToAnInputOnlyStream;+}+++/* NOTE: the following functions are MME-stream specific, and are called directly+    by client code. We need to check for many more error conditions here because+    we don't have the benefit of pa_front.c's parameter checking.+*/++static PaError GetWinMMEStreamPointer( PaWinMmeStream **stream, PaStream *s )+{+    PaError result;+    PaUtilHostApiRepresentation *hostApi;+    PaWinMmeHostApiRepresentation *winMmeHostApi;+    +    result = PaUtil_ValidateStreamPointer( s );+    if( result != paNoError )+        return result;++    result = PaUtil_GetHostApiRepresentation( &hostApi, paMME );+    if( result != paNoError )+        return result;++    winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;+    +    /* note, the following would be easier if there was a generic way of testing+        that a stream belongs to a specific host API */+    +    if( PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->callbackStreamInterface+            || PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->blockingStreamInterface )+    {+        /* s is a WinMME stream */+        *stream = (PaWinMmeStream *)s;+        return paNoError;+    }+    else+    {+        return paIncompatibleStreamHostApi;+    }+}+++int PaWinMME_GetStreamInputHandleCount( PaStream* s )+{+    PaWinMmeStream *stream;+    PaError result = GetWinMMEStreamPointer( &stream, s );++    if( result == paNoError )+        return (PA_IS_INPUT_STREAM_(stream)) ? stream->input.deviceCount : 0;+    else+        return result;+}+++HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* s, int handleIndex )+{+    PaWinMmeStream *stream;+    PaError result = GetWinMMEStreamPointer( &stream, s );++    if( result == paNoError+            && PA_IS_INPUT_STREAM_(stream)+            && handleIndex >= 0+            && (unsigned int)handleIndex < stream->input.deviceCount )+        return ((HWAVEIN*)stream->input.waveHandles)[handleIndex];+    else+        return 0;+}+++int PaWinMME_GetStreamOutputHandleCount( PaStream* s)+{+    PaWinMmeStream *stream;+    PaError result = GetWinMMEStreamPointer( &stream, s );++    if( result == paNoError )+        return (PA_IS_OUTPUT_STREAM_(stream)) ? stream->output.deviceCount : 0;+    else+        return result;+}+++HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* s, int handleIndex )+{+    PaWinMmeStream *stream;+    PaError result = GetWinMMEStreamPointer( &stream, s );++    if( result == paNoError+            && PA_IS_OUTPUT_STREAM_(stream)+            && handleIndex >= 0+            && (unsigned int)handleIndex < stream->output.deviceCount )+        return ((HWAVEOUT*)stream->output.waveHandles)[handleIndex];+    else+        return 0;+}
+ portaudio/src/os/win/pa_win_coinitialize.c view
@@ -0,0 +1,144 @@+/*
+ * Microsoft COM initialization routines
+ * Copyright (c) 1999-2011 Ross Bencina, Dmitry Kostjuchenko
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2011 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+
+ @brief Microsoft COM initialization routines.
+*/
+
+#include <windows.h>
+#include <objbase.h>
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_debugprint.h"
+
+#include "pa_win_coinitialize.h"
+
+
+#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) && !defined(_WIN32_WCE) /* MSC version 6 and above */
+#pragma comment( lib, "ole32.lib" )
+#endif
+
+
+/* use some special bit patterns here to try to guard against uninitialized memory errors */
+#define PAWINUTIL_COM_INITIALIZED       (0xb38f)
+#define PAWINUTIL_COM_NOT_INITIALIZED   (0xf1cd)
+
+
+PaError PaWinUtil_CoInitialize( PaHostApiTypeId hostApiType, PaWinUtilComInitializationResult *comInitializationResult )
+{
+    HRESULT hr;
+
+    comInitializationResult->state = PAWINUTIL_COM_NOT_INITIALIZED;
+
+    /*
+        If COM is already initialized CoInitialize will either return
+        FALSE, or RPC_E_CHANGED_MODE if it was initialised in a different
+        threading mode. In either case we shouldn't consider it an error
+        but we need to be careful to not call CoUninitialize() if 
+        RPC_E_CHANGED_MODE was returned.
+    */
+
+    hr = CoInitialize(0); /* use legacy-safe equivalent to CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) */
+    if( FAILED(hr) && hr != RPC_E_CHANGED_MODE )
+    {
+        PA_DEBUG(("CoInitialize(0) failed. hr=%d\n", hr));
+
+        if( hr == E_OUTOFMEMORY )
+            return paInsufficientMemory;
+
+        {
+            char *lpMsgBuf;
+            FormatMessage(
+                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+                NULL,
+                hr,
+                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                (LPTSTR) &lpMsgBuf,
+                0,
+                NULL
+            );
+            PaUtil_SetLastHostErrorInfo( hostApiType, hr, lpMsgBuf );
+            LocalFree( lpMsgBuf );
+        }
+
+        return paUnanticipatedHostError;
+    }
+
+    if( hr != RPC_E_CHANGED_MODE )
+    {
+        comInitializationResult->state = PAWINUTIL_COM_INITIALIZED;
+
+        /*
+            Memorize calling thread id and report warning on Uninitialize if 
+            calling thread is different as CoInitialize must match CoUninitialize 
+            in the same thread.
+        */
+        comInitializationResult->initializingThreadId = GetCurrentThreadId();
+    }
+
+    return paNoError;
+}
+
+
+void PaWinUtil_CoUninitialize( PaHostApiTypeId hostApiType, PaWinUtilComInitializationResult *comInitializationResult )
+{
+    if( comInitializationResult->state != PAWINUTIL_COM_NOT_INITIALIZED
+            && comInitializationResult->state != PAWINUTIL_COM_INITIALIZED ){
+    
+        PA_DEBUG(("ERROR: PaWinUtil_CoUninitialize called without calling PaWinUtil_CoInitialize\n"));
+    }
+
+    if( comInitializationResult->state == PAWINUTIL_COM_INITIALIZED )
+    {
+        DWORD currentThreadId = GetCurrentThreadId();
+		if( comInitializationResult->initializingThreadId != currentThreadId )
+		{
+			PA_DEBUG(("ERROR: failed PaWinUtil_CoUninitialize calling thread[%d] does not match initializing thread[%d]\n",
+				currentThreadId, comInitializationResult->initializingThreadId));
+		}
+		else
+		{
+			CoUninitialize();
+
+            comInitializationResult->state = PAWINUTIL_COM_NOT_INITIALIZED;
+		}
+    }
+}
+ portaudio/src/os/win/pa_win_hostapis.c view
@@ -0,0 +1,102 @@+/*+ * $Id: pa_win_hostapis.c 1728 2011-08-18 03:31:51Z rossb $+ * Portable Audio I/O Library Windows initialization table+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2008 Ross Bencina, Phil Burk+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup win_src++    @brief Win32 host API initialization function table.+*/++/* This is needed to make this source file depend on CMake option changes+   and at the same time make it transparent for clients not using CMake.+*/+#ifdef PORTAUDIO_CMAKE_GENERATED+#include "options_cmake.h"+#endif++#include "pa_hostapi.h"+++#ifdef __cplusplus+extern "C"+{+#endif /* __cplusplus */++PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );+PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );+PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );+PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );++#ifdef __cplusplus+}+#endif /* __cplusplus */+++PaUtilHostApiInitializer *paHostApiInitializers[] =+    {++#if PA_USE_WMME+        PaWinMme_Initialize,+#endif++#if PA_USE_DS+        PaWinDs_Initialize,+#endif++#if PA_USE_ASIO+        PaAsio_Initialize,+#endif++#if PA_USE_WASAPI+		PaWasapi_Initialize,+#endif++#if PA_USE_WDMKS+        PaWinWdm_Initialize,+#endif++#if PA_USE_SKELETON+        PaSkeleton_Initialize, /* just for testing. last in list so it isn't marked as default. */+#endif++        0   /* NULL terminated array */+    };++
+ portaudio/src/os/win/pa_win_util.c view
@@ -0,0 +1,153 @@+/*+ * $Id: pa_win_util.c 1584 2011-02-02 18:58:17Z rossb $+ * Portable Audio I/O Library+ * Win32 platform-specific support functions+ *+ * Based on the Open Source API proposed by Ross Bencina+ * Copyright (c) 1999-2008 Ross Bencina+ *+ * Permission is hereby granted, free of charge, to any person obtaining+ * a copy of this software and associated documentation files+ * (the "Software"), to deal in the Software without restriction,+ * including without limitation the rights to use, copy, modify, merge,+ * publish, distribute, sublicense, and/or sell copies of the Software,+ * and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be+ * included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.+ */++/*+ * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests:+ *+ * Any person wishing to distribute modifications to the Software is+ * requested to send the modifications to the original developer so that+ * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above.+ */++/** @file+ @ingroup win_src++ @brief Win32 implementation of platform-specific PaUtil support functions.+*/+ +#include <windows.h>+#include <mmsystem.h> /* for timeGetTime() */++#include "pa_util.h"++#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) && !defined(_WIN32_WCE) /* MSC version 6 and above */+#pragma comment( lib, "winmm.lib" )+#endif+++/*+   Track memory allocations to avoid leaks.+ */++#if PA_TRACK_MEMORY+static int numAllocations_ = 0;+#endif+++void *PaUtil_AllocateMemory( long size )+{+    void *result = GlobalAlloc( GPTR, size );++#if PA_TRACK_MEMORY+    if( result != NULL ) numAllocations_ += 1;+#endif+    return result;+}+++void PaUtil_FreeMemory( void *block )+{+    if( block != NULL )+    {+        GlobalFree( block );+#if PA_TRACK_MEMORY+        numAllocations_ -= 1;+#endif++    }+}+++int PaUtil_CountCurrentlyAllocatedBlocks( void )+{+#if PA_TRACK_MEMORY+    return numAllocations_;+#else+    return 0;+#endif+}+++void Pa_Sleep( long msec )+{+    Sleep( msec );+}++static int usePerformanceCounter_;+static double secondsPerTick_;++void PaUtil_InitializeClock( void )+{+    LARGE_INTEGER ticksPerSecond;++    if( QueryPerformanceFrequency( &ticksPerSecond ) != 0 )+    {+        usePerformanceCounter_ = 1;+        secondsPerTick_ = 1.0 / (double)ticksPerSecond.QuadPart;+    }+    else+    {+        usePerformanceCounter_ = 0;+    }+}+++double PaUtil_GetTime( void )+{+    LARGE_INTEGER time;++    if( usePerformanceCounter_ )+    {+        /*+            Note: QueryPerformanceCounter has a known issue where it can skip forward+            by a few seconds (!) due to a hardware bug on some PCI-ISA bridge hardware.+            This is documented here:+            http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323&++            The work-arounds are not very paletable and involve querying GetTickCount +            at every time step.++            Using rdtsc is not a good option on multi-core systems.++            For now we just use QueryPerformanceCounter(). It's good, most of the time.+        */+        QueryPerformanceCounter( &time );+        return time.QuadPart * secondsPerTick_;+    }+    else+    {+#ifndef UNDER_CE    	+        return timeGetTime() * .001;+#else+        return GetTickCount() * .001;+#endif                +    }+}
+ portaudio/src/os/win/pa_win_waveformat.c view
@@ -0,0 +1,158 @@+/*
+ * PortAudio Portable Real-Time Audio Library
+ * Windows WAVEFORMAT* data structure utilities
+ * portaudio.h should be included before this file.
+ *
+ * Copyright (c) 2007 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+#include <windows.h>
+#include <mmsystem.h>
+
+#include "portaudio.h"
+#include "pa_win_waveformat.h"
+
+
+#if !defined(WAVE_FORMAT_EXTENSIBLE)
+#define  WAVE_FORMAT_EXTENSIBLE         0xFFFE
+#endif
+
+static GUID pawin_ksDataFormatSubtypeGuidBase = 
+	{ (USHORT)(WAVE_FORMAT_PCM), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 };
+
+
+int PaWin_SampleFormatToLinearWaveFormatTag( PaSampleFormat sampleFormat )
+{
+    if( sampleFormat == paFloat32 )
+        return PAWIN_WAVE_FORMAT_IEEE_FLOAT;
+    
+    return PAWIN_WAVE_FORMAT_PCM;
+}
+
+
+void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat, 
+		int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate )
+{
+	WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat;
+    int bytesPerSample = Pa_GetSampleSize(sampleFormat);
+	unsigned long bytesPerFrame = numChannels * bytesPerSample;
+	
+    waveFormatEx->wFormatTag = waveFormatTag;
+	waveFormatEx->nChannels = (WORD)numChannels;
+	waveFormatEx->nSamplesPerSec = (DWORD)sampleRate;
+	waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame;
+	waveFormatEx->nBlockAlign = (WORD)bytesPerFrame;
+	waveFormatEx->wBitsPerSample = bytesPerSample * 8;
+	waveFormatEx->cbSize = 0;
+}
+
+
+void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat, 
+		int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate,
+		PaWinWaveFormatChannelMask channelMask )
+{
+	WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat;
+    int bytesPerSample = Pa_GetSampleSize(sampleFormat);
+	unsigned long bytesPerFrame = numChannels * bytesPerSample;
+    GUID guid;
+
+	waveFormatEx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
+	waveFormatEx->nChannels = (WORD)numChannels;
+	waveFormatEx->nSamplesPerSec = (DWORD)sampleRate;
+	waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame;
+	waveFormatEx->nBlockAlign = (WORD)bytesPerFrame;
+	waveFormatEx->wBitsPerSample = bytesPerSample * 8;
+	waveFormatEx->cbSize = 22;
+
+	*((WORD*)&waveFormat->fields[PAWIN_INDEXOF_WVALIDBITSPERSAMPLE]) =
+			waveFormatEx->wBitsPerSample;
+
+	*((DWORD*)&waveFormat->fields[PAWIN_INDEXOF_DWCHANNELMASK]) = channelMask;
+		
+    guid = pawin_ksDataFormatSubtypeGuidBase;
+    guid.Data1 = (USHORT)waveFormatTag;
+    *((GUID*)&waveFormat->fields[PAWIN_INDEXOF_SUBFORMAT]) = guid;
+}
+
+PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels )
+{
+	switch( numChannels ){
+		case 1:
+			return PAWIN_SPEAKER_MONO;
+		case 2:
+			return PAWIN_SPEAKER_STEREO; 
+		case 3:
+            return PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_FRONT_RIGHT;
+		case 4:
+			return PAWIN_SPEAKER_QUAD;
+		case 5:
+            return PAWIN_SPEAKER_QUAD | PAWIN_SPEAKER_FRONT_CENTER;
+		case 6:
+            /* The meaning of the PAWIN_SPEAKER_5POINT1 flag has changed over time:
+                http://msdn2.microsoft.com/en-us/library/aa474707.aspx
+               We use PAWIN_SPEAKER_5POINT1 (not PAWIN_SPEAKER_5POINT1_SURROUND)
+               because on some cards (eg Audigy) PAWIN_SPEAKER_5POINT1_SURROUND 
+               results in a virtual mixdown placing the rear output in the 
+               front _and_ rear speakers.
+            */
+			return PAWIN_SPEAKER_5POINT1; 
+        /* case 7: */
+		case 8:
+            /* RoBi: PAWIN_SPEAKER_7POINT1_SURROUND fits normal surround sound setups better than PAWIN_SPEAKER_7POINT1, f.i. NVidia HDMI Audio
+               output is silent on channels 5&6 with NVidia drivers, and channel 7&8 with Micrsoft HD Audio driver using PAWIN_SPEAKER_7POINT1. 
+               With PAWIN_SPEAKER_7POINT1_SURROUND both setups work OK. */
+			return PAWIN_SPEAKER_7POINT1_SURROUND;
+	}
+
+    /* Apparently some Audigy drivers will output silence 
+       if the direct-out constant (0) is used. So this is not ideal.    
+
+       RoBi 2012-12-19: Also, NVidia driver seem to output garbage instead. Again not very ideal.
+    */
+	return  PAWIN_SPEAKER_DIRECTOUT;
+
+    /* Note that Alec Rogers proposed the following as an alternate method to 
+        generate the default channel mask, however it doesn't seem to be an improvement
+        over the above, since some drivers will matrix outputs mapping to non-present
+        speakers accross multiple physical speakers.
+
+        if(nChannels==1) {
+            pwfFormat->dwChannelMask = SPEAKER_FRONT_CENTER;
+        }
+        else {
+            pwfFormat->dwChannelMask = 0;
+            for(i=0; i<nChannels; i++)
+                pwfFormat->dwChannelMask = (pwfFormat->dwChannelMask << 1) | 0x1;
+        }
+    */
+}
+ portaudio/src/os/win/pa_win_wdmks_utils.c view
@@ -0,0 +1,308 @@+/*
+ * PortAudio Portable Real-Time Audio Library
+ * Windows WDM KS utilities
+ *
+ * Copyright (c) 1999 - 2007 Andrew Baldwin, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+#include <windows.h>
+#include <mmreg.h>
+#ifndef WAVE_FORMAT_IEEE_FLOAT
+    #define WAVE_FORMAT_IEEE_FLOAT 0x0003   // MinGW32 does not define this
+#endif    
+#ifndef _WAVEFORMATEXTENSIBLE_
+    #define _WAVEFORMATEXTENSIBLE_          // MinGW32 does not define this
+#endif
+#ifndef _INC_MMREG
+    #define _INC_MMREG                      // for STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
+#endif
+#include <winioctl.h>						// MinGW32 does not define this automatically
+
+#if defined(__GNUC__)
+
+#include "../../hostapi/wasapi/mingw-include/ks.h"
+#include "../../hostapi/wasapi/mingw-include/ksmedia.h"
+
+#else
+
+#include <ks.h>
+#include <ksmedia.h>
+
+#endif
+
+#include <stdio.h>                          // just for some development printfs
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_win_wdmks_utils.h"
+
+#if !defined(PA_WDMKS_NO_KSGUID_LIB) && !defined(PAWIN_WDMKS_NO_KSGUID_LIB) && !defined(__GNUC__)
+    #if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
+        #pragma comment( lib, "ksguid.lib" )
+    #endif
+    #define pa_KSDATAFORMAT_TYPE_AUDIO            KSDATAFORMAT_TYPE_AUDIO
+    #define pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT    KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
+    #define pa_KSDATAFORMAT_SUBTYPE_PCM           KSDATAFORMAT_SUBTYPE_PCM
+    #define pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX  KSDATAFORMAT_SUBTYPE_WAVEFORMATEX
+    #define pa_KSMEDIUMSETID_Standard             KSMEDIUMSETID_Standard
+    #define pa_KSINTERFACESETID_Standard          KSINTERFACESETID_Standard
+    #define pa_KSPROPSETID_Pin                    KSPROPSETID_Pin
+#else
+    static const GUID pa_KSDATAFORMAT_TYPE_AUDIO            = { STATIC_KSDATAFORMAT_TYPE_AUDIO };
+    static const GUID pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT    = { STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT };
+    static const GUID pa_KSDATAFORMAT_SUBTYPE_PCM           = { STATIC_KSDATAFORMAT_SUBTYPE_PCM };
+    static const GUID pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX  = { STATIC_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX };
+    static const GUID pa_KSMEDIUMSETID_Standard             = { STATIC_KSMEDIUMSETID_Standard };
+    static const GUID pa_KSINTERFACESETID_Standard          = { STATIC_KSINTERFACESETID_Standard };
+    static const GUID pa_KSPROPSETID_Pin                    = { STATIC_KSPROPSETID_Pin };
+#endif
+
+
+#define pa_IS_VALID_WAVEFORMATEX_GUID(Guid)\
+    (!memcmp(((PUSHORT)&pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX) + 1, ((PUSHORT)(Guid)) + 1, sizeof(GUID) - sizeof(USHORT)))
+
+
+
+static PaError WdmGetPinPropertySimple(
+    HANDLE  handle,
+    unsigned long pinId,
+    unsigned long property,
+    void* value,
+    unsigned long valueSize )
+{
+    DWORD bytesReturned;
+    KSP_PIN ksPProp;
+    ksPProp.Property.Set = pa_KSPROPSETID_Pin;
+    ksPProp.Property.Id = property;
+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
+    ksPProp.PinId = pinId;
+    ksPProp.Reserved = 0;
+
+    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN),
+            value, valueSize, &bytesReturned, NULL ) == 0 || bytesReturned != valueSize )
+    {
+        return paUnanticipatedHostError;
+    }
+    else
+    {
+        return paNoError;
+    }
+}
+
+
+static PaError WdmGetPinPropertyMulti(
+    HANDLE handle,
+    unsigned long pinId,
+    unsigned long property,
+    KSMULTIPLE_ITEM** ksMultipleItem)
+{
+    unsigned long multipleItemSize = 0;
+    KSP_PIN ksPProp;
+    DWORD bytesReturned;
+
+    *ksMultipleItem = 0;
+
+    ksPProp.Property.Set = pa_KSPROPSETID_Pin;
+    ksPProp.Property.Id = property;
+    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
+    ksPProp.PinId = pinId;
+    ksPProp.Reserved = 0;
+
+    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp.Property,
+            sizeof(KSP_PIN), NULL, 0, &multipleItemSize, NULL ) == 0 && GetLastError() != ERROR_MORE_DATA )
+    {
+        return paUnanticipatedHostError;
+    }
+
+    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
+    if( !*ksMultipleItem )
+    {
+        return paInsufficientMemory;
+    }
+
+    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN),
+            (void*)*ksMultipleItem,  multipleItemSize, &bytesReturned, NULL ) == 0 || bytesReturned != multipleItemSize )
+    {
+        PaUtil_FreeMemory( ksMultipleItem );
+        return paUnanticipatedHostError;
+    }
+
+    return paNoError;
+}
+
+
+static int GetKSFilterPinCount( HANDLE deviceHandle )
+{
+    DWORD result;
+
+    if( WdmGetPinPropertySimple( deviceHandle, 0, KSPROPERTY_PIN_CTYPES, &result, sizeof(result) ) == paNoError ){
+        return result;
+    }else{
+        return 0;
+    }
+}
+
+
+static KSPIN_COMMUNICATION GetKSFilterPinPropertyCommunication( HANDLE deviceHandle, int pinId )
+{
+    KSPIN_COMMUNICATION result;
+
+    if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_COMMUNICATION, &result, sizeof(result) ) == paNoError ){
+        return result;
+    }else{
+        return KSPIN_COMMUNICATION_NONE;
+    }
+}
+
+
+static KSPIN_DATAFLOW GetKSFilterPinPropertyDataflow( HANDLE deviceHandle, int pinId )
+{
+    KSPIN_DATAFLOW result;
+
+    if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_DATAFLOW, &result, sizeof(result) ) == paNoError ){
+        return result;
+    }else{
+        return (KSPIN_DATAFLOW)0;
+    }
+}
+
+
+static int KSFilterPinPropertyIdentifiersInclude( 
+        HANDLE deviceHandle, int pinId, unsigned long property, const GUID *identifierSet, unsigned long identifierId  )
+{
+    KSMULTIPLE_ITEM* item = NULL;
+    KSIDENTIFIER* identifier;
+    int i;
+    int result = 0;
+
+    if( WdmGetPinPropertyMulti( deviceHandle, pinId, property, &item) != paNoError )
+        return 0;
+    
+    identifier = (KSIDENTIFIER*)(item+1);
+
+    for( i = 0; i < (int)item->Count; i++ )
+    {
+        if( !memcmp( (void*)&identifier[i].Set, (void*)identifierSet, sizeof( GUID ) ) &&
+           ( identifier[i].Id == identifierId ) )
+        {
+            result = 1;
+            break;
+        }
+    }
+
+    PaUtil_FreeMemory( item );
+
+    return result;
+}
+
+
+/* return the maximum channel count supported by any pin on the device. 
+   if isInput is non-zero we query input pins, otherwise output pins.
+*/
+int PaWin_WDMKS_QueryFilterMaximumChannelCount( void *wcharDevicePath, int isInput )
+{
+    HANDLE deviceHandle;
+	ULONG i;
+    int pinCount, pinId;
+    int result = 0;
+    KSPIN_DATAFLOW requiredDataflowDirection = (isInput ? KSPIN_DATAFLOW_OUT : KSPIN_DATAFLOW_IN );
+    
+    if( !wcharDevicePath )
+        return 0;
+
+    deviceHandle = CreateFileW( (LPCWSTR)wcharDevicePath, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
+    if( deviceHandle == INVALID_HANDLE_VALUE )
+        return 0;
+
+    pinCount = GetKSFilterPinCount( deviceHandle );
+    for( pinId = 0; pinId < pinCount; ++pinId )
+    {
+        KSPIN_COMMUNICATION communication = GetKSFilterPinPropertyCommunication( deviceHandle, pinId );
+        KSPIN_DATAFLOW dataflow = GetKSFilterPinPropertyDataflow( deviceHandle, pinId );
+        if( ( dataflow == requiredDataflowDirection ) &&
+                (( communication == KSPIN_COMMUNICATION_SINK) ||
+                 ( communication == KSPIN_COMMUNICATION_BOTH)) 
+             && ( KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
+                    KSPROPERTY_PIN_INTERFACES, &pa_KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_STREAMING )
+                || KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
+                    KSPROPERTY_PIN_INTERFACES, &pa_KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_LOOPED_STREAMING ) )
+             && KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
+                    KSPROPERTY_PIN_MEDIUMS, &pa_KSMEDIUMSETID_Standard, KSMEDIUM_STANDARD_DEVIO ) )
+         {
+            KSMULTIPLE_ITEM* item = NULL;
+            if( WdmGetPinPropertyMulti( deviceHandle, pinId, KSPROPERTY_PIN_DATARANGES, &item ) == paNoError )
+            {
+                KSDATARANGE *dataRange = (KSDATARANGE*)(item+1);
+
+                for( i=0; i < item->Count; ++i ){
+
+                    if( pa_IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat)
+                            || memcmp( (void*)&dataRange->SubFormat, (void*)&pa_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID) ) == 0
+                            || memcmp( (void*)&dataRange->SubFormat, (void*)&pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID) ) == 0
+                            || ( ( memcmp( (void*)&dataRange->MajorFormat, (void*)&pa_KSDATAFORMAT_TYPE_AUDIO, sizeof(GUID) ) == 0 )
+                                && ( memcmp( (void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_WILDCARD, sizeof(GUID) ) == 0 ) ) )
+                    {
+                        KSDATARANGE_AUDIO *dataRangeAudio = (KSDATARANGE_AUDIO*)dataRange;
+                        
+                        /*
+                        printf( ">>> %d %d %d %d %S\n", isInput, dataflow, communication, dataRangeAudio->MaximumChannels, devicePath );
+                       
+                        if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WAVEFORMATEX, sizeof(GUID) ) == 0 )
+                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WAVEFORMATEX\n" );
+                        else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_DSOUND, sizeof(GUID) ) == 0 )
+                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_DSOUND\n" );
+                        else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WILDCARD, sizeof(GUID) ) == 0 )
+                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WILDCARD\n" );
+                        else
+                            printf( "\tspecifier: ?\n" );
+                        */
+
+                        /*
+                            We assume that very high values for MaximumChannels are not useful and indicate
+                            that the driver isn't prepared to tell us the real number of channels which it supports.
+                        */
+                        if( dataRangeAudio->MaximumChannels  < 0xFFFFUL && (int)dataRangeAudio->MaximumChannels > result )
+                            result = (int)dataRangeAudio->MaximumChannels;
+                    }
+                    
+                    dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize);
+                }
+
+                PaUtil_FreeMemory( item );
+            }
+        }
+    }
+    
+    CloseHandle( deviceHandle );
+    return result;
+}