pa_win_wdmks.c 233 KB
Newer Older
bjornroche's avatar
bjornroche committed
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
* $Id$
* 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.
*/
bjornroche's avatar
bjornroche committed
28 29

/*
30 31 32 33 34 35 36 37 38
* 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.
*/
bjornroche's avatar
bjornroche committed
39 40

/** @file
41 42 43 44 45 46 47 48 49 50
@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
bjornroche's avatar
bjornroche committed
51 52 53 54
*/

#include <stdio.h>

robiwan's avatar
WDM-KS:  
robiwan committed
55
#if (defined(_WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
56 57 58
#pragma comment( lib, "setupapi.lib" )
#endif

bjornroche's avatar
bjornroche committed
59 60 61 62 63 64
/* Debugging/tracing support */

#define PA_LOGE_
#define PA_LOGL_

#ifdef __GNUC__
65 66 67
#include <initguid.h>
#define _WIN32_WINNT 0x0501
#define WINVER 0x0501
bjornroche's avatar
bjornroche committed
68 69 70 71
#endif

#include <string.h> /* strlen() */
#include <assert.h>
72
#include <wchar.h>  /* iswspace() */
bjornroche's avatar
bjornroche committed
73 74 75 76 77 78 79 80 81

#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"
82 83 84 85 86 87
#include "pa_memorybarrier.h"
#include "pa_ringbuffer.h"
#include "pa_trace.h"
#include "pa_win_waveformat.h"

#include "pa_win_wdmks.h"
bjornroche's avatar
bjornroche committed
88

89 90 91 92 93 94 95
#ifndef DRV_QUERYDEVICEINTERFACE
#define DRV_QUERYDEVICEINTERFACE     (DRV_RESERVED + 12)
#endif
#ifndef DRV_QUERYDEVICEINTERFACESIZE
#define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)
#endif

bjornroche's avatar
bjornroche committed
96 97
#include <windows.h>
#include <winioctl.h>
98
#include <process.h>
bjornroche's avatar
bjornroche committed
99

100
#include <math.h>
bjornroche's avatar
bjornroche committed
101

102 103 104
#ifdef _MSC_VER
#define snprintf _snprintf
#define vsnprintf _vsnprintf
rob_bielik's avatar
rob_bielik committed
105 106
#endif

107 108 109 110
/* 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 ;
gordon_gidluck's avatar
gordon_gidluck committed
111
#else
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
#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)
gordon_gidluck's avatar
gordon_gidluck committed
148 149
#endif

150 151 152 153
/* 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
gordon_gidluck's avatar
gordon_gidluck committed
154
#else
155 156
#define CREATE_THREAD_FUNCTION CreateThread
#define PA_THREAD_FUNC static DWORD WINAPI
gordon_gidluck's avatar
gordon_gidluck committed
157 158
#endif

bjornroche's avatar
bjornroche committed
159
#ifdef _MSC_VER
160 161 162 163 164 165 166
#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)
bjornroche's avatar
bjornroche committed
167 168
#endif

169
#include <setupapi.h>
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

#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

185
#include <mmreg.h>
bjornroche's avatar
bjornroche committed
186
#include <ks.h>
187 188 189 190

/* 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 */
bjornroche's avatar
bjornroche committed
191
#include <ksmedia.h>
192

193 194
#endif

bjornroche's avatar
bjornroche committed
195 196 197 198
#include <assert.h>
#include <stdio.h>

/* These next definitions allow the use of the KSUSER DLL */
199
typedef /*KSDDKAPI*/ DWORD WINAPI KSCREATEPIN(HANDLE, PKSPIN_CONNECT, ACCESS_MASK, PHANDLE);
bjornroche's avatar
bjornroche committed
200 201 202
extern HMODULE      DllKsUser;
extern KSCREATEPIN* FunctionKsCreatePin;

203 204 205 206 207 208 209 210
/* 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;
211 212 213 214 215 216 217 218 219 220 221

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};
222 223 224 225 226

/* An unspecified channel count (-1) is not treated correctly, so we replace it with
* an arbitrarily large number */ 
#define MAXIMUM_NUMBER_OF_CHANNELS 256

bjornroche's avatar
bjornroche committed
227 228 229 230
/* Forward definition to break circular type reference between pin and filter */
struct __PaWinWdmFilter;
typedef struct __PaWinWdmFilter PaWinWdmFilter;

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
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;

bjornroche's avatar
bjornroche committed
265
/* The Pin structure
266 267
* A pin is an input or output node, e.g. for audio flow */
struct __PaWinWdmPin
bjornroche's avatar
bjornroche committed
268 269
{
    HANDLE                      handle;
270 271 272 273
    PaWinWdmMuxedInput**        inputs;
    unsigned                    inputCount;
    wchar_t                     friendlyName[MAX_PATH];

bjornroche's avatar
bjornroche committed
274
    PaWinWdmFilter*             parentFilter;
275
    PaWDMKSSubType              pinKsSubType;
bjornroche's avatar
bjornroche committed
276
    unsigned long               pinId;
277
    unsigned long               endpointPinId;  /* For output pins */
bjornroche's avatar
bjornroche committed
278 279 280 281 282 283 284 285 286 287 288
    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;
robiwan's avatar
robiwan committed
289
    int                         defaultSampleRate;
290 291 292 293 294 295 296
    ULONG                       *positionRegister;  /* WaveRT */
    ULONG                       hwLatency;          /* WaveRT */
    FunctionMemoryBarrier       fnMemBarrier;       /* WaveRT */
    FunctionGetPinAudioPosition fnAudioPosition;    /* WaveRT */
    FunctionPinHandler          fnEventHandler;
    FunctionPinHandler          fnSubmitHandler;
};
bjornroche's avatar
bjornroche committed
297 298

/* The Filter structure
299
* A filter has a number of pins and a "friendly name" */
bjornroche's avatar
bjornroche committed
300 301 302
struct __PaWinWdmFilter
{
    HANDLE         handle;
303 304 305
    PaWinWDMKSDeviceInfo    devInfo;  /* This will hold information that is exposed in PaDeviceInfo */

    DWORD            deviceNode;
bjornroche's avatar
bjornroche committed
306 307
    int            pinCount;
    PaWinWdmPin**  pins;
308 309 310
    PaWinWdmFilter*  topologyFilter;
    wchar_t          friendlyName[MAX_PATH];
    int              validPinCount;
bjornroche's avatar
bjornroche committed
311
    int            usageCount;
312 313 314
    KSMULTIPLE_ITEM* connections;
    KSMULTIPLE_ITEM* nodes;
    int              filterRefCount;
bjornroche's avatar
bjornroche committed
315 316
};

317 318 319 320 321 322 323 324 325 326 327 328

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;

bjornroche's avatar
bjornroche committed
329 330 331 332 333 334 335 336
/* PaWinWdmHostApiRepresentation - host api datastructure specific to this implementation */
typedef struct __PaWinWdmHostApiRepresentation
{
    PaUtilHostApiRepresentation  inheritedHostApiRep;
    PaUtilStreamInterface        callbackStreamInterface;
    PaUtilStreamInterface        blockingStreamInterface;

    PaUtilAllocationGroup*       allocations;
337
    int                          deviceCount;
bjornroche's avatar
bjornroche committed
338 339 340 341 342 343 344 345 346
}
PaWinWdmHostApiRepresentation;

typedef struct __DATAPACKET
{
    KSSTREAM_HEADER  Header;
    OVERLAPPED       Signal;
} DATAPACKET;

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
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;

bjornroche's avatar
bjornroche committed
370
/* PaWinWdmStream - a stream data structure specifically for this implementation */
371
struct __PaWinWdmStream
bjornroche's avatar
bjornroche committed
372 373
{
    PaUtilStreamRepresentation  streamRepresentation;
374
    PaWDMKSSpecificStreamInfo   hostApiStreamInfo;    /* This holds info that is exposed through PaStreamInfo */
bjornroche's avatar
bjornroche committed
375 376 377
    PaUtilCpuLoadMeasurer       cpuLoadMeasurer;
    PaUtilBufferProcessor       bufferProcessor;

378 379 380 381 382 383 384
#if PA_TRACE_REALTIME_EVENTS
    LogHandle                   hLog;
#endif

    PaUtilAllocationGroup*      allocGroup;
    PaWinWdmIOInfo              capture;
    PaWinWdmIOInfo              render;
bjornroche's avatar
bjornroche committed
385 386 387 388 389 390
    int                         streamStarted;
    int                         streamActive;
    int                         streamStop;
    int                         streamAbort;
    int                         oldProcessPriority;
    HANDLE                      streamThread;
391 392 393
    HANDLE                      eventAbort;
    HANDLE                      eventStreamStart[StreamStart_kCnt];        /* 0 = OK, 1 = Failed */
    PaError                     threadResult;
bjornroche's avatar
bjornroche committed
394
    PaStreamFlags               streamFlags;
395 396 397 398 399

    /* Capture ring buffer */
    PaUtilRingBuffer            ringBuffer;
    char*                       ringBufferData;

bjornroche's avatar
bjornroche committed
400
    /* These values handle the case where the user wants to use fewer
401
    * channels than the device has */
bjornroche's avatar
bjornroche committed
402 403 404 405
    int                         userInputChannels;
    int                         deviceInputChannels;
    int                         userOutputChannels;
    int                         deviceOutputChannels;
406
};
bjornroche's avatar
bjornroche committed
407

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
/* 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;
bjornroche's avatar
bjornroche committed
436 437 438 439 440 441 442 443 444 445 446

HMODULE      DllKsUser = NULL;
KSCREATEPIN* FunctionKsCreatePin = NULL;

/* prototypes for functions declared in this file */

#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */

447
    PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
bjornroche's avatar
bjornroche committed
448 449 450 451 452 453 454

#ifdef __cplusplus
}
#endif /* __cplusplus */

/* Low level I/O functions */
static PaError WdmSyncIoctl(HANDLE handle,
455 456 457 458 459 460
                            unsigned long ioctlNumber,
                            void* inBuffer,
                            unsigned long inBufferCount,
                            void* outBuffer,
                            unsigned long outBufferCount,
                            unsigned long* bytesReturned);
461

bjornroche's avatar
bjornroche committed
462
static PaError WdmGetPropertySimple(HANDLE handle,
463 464 465
                                    const GUID* const guidPropertySet,
                                    unsigned long property,
                                    void* value,
466 467
                                    unsigned long valueCount);

bjornroche's avatar
bjornroche committed
468
static PaError WdmSetPropertySimple(HANDLE handle,
469 470 471 472 473 474 475
                                    const GUID* const guidPropertySet,
                                    unsigned long property,
                                    void* value,
                                    unsigned long valueCount,
                                    void* instance,
                                    unsigned long instanceCount);

bjornroche's avatar
bjornroche committed
476
static PaError WdmGetPinPropertySimple(HANDLE  handle,
477 478 479 480 481 482
                                       unsigned long pinId,
                                       const GUID* const guidPropertySet,
                                       unsigned long property,
                                       void* value,
                                       unsigned long valueCount,
                                       unsigned long* byteCount);
483

bjornroche's avatar
bjornroche committed
484
static PaError WdmGetPinPropertyMulti(HANDLE  handle,
485 486 487 488
                                      unsigned long pinId,
                                      const GUID* const guidPropertySet,
                                      unsigned long property,
                                      KSMULTIPLE_ITEM** ksMultipleItem);
489

490 491 492 493 494 495 496 497 498
static PaError WdmGetPropertyMulti(HANDLE handle,
                                   const GUID* const guidPropertySet,
                                   unsigned long property,
                                   KSMULTIPLE_ITEM** ksMultipleItem);

static PaError WdmSetMuxNodeProperty(HANDLE handle,
                                     ULONG nodeId,
                                     ULONG pinId);

bjornroche's avatar
bjornroche committed
499 500 501 502 503 504 505 506 507 508

/** 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);
509 510 511 512 513 514 515
/* 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);
516 517 518
static PaError PinGetAudioPositionMemoryMapped(PaWinWdmPin* pPin, ULONG* pPosition);
static PaError PinGetAudioPositionViaIOCTLRead(PaWinWdmPin* pPin, ULONG* pPosition);
static PaError PinGetAudioPositionViaIOCTLWrite(PaWinWdmPin* pPin, ULONG* pPosition);
bjornroche's avatar
bjornroche committed
519 520

/* Filter management functions */
521 522
static PaWinWdmFilter* FilterNew(PaWDMKSType type, DWORD devNode, const wchar_t* filterName, const wchar_t* friendlyName, PaError* error);
static PaError FilterInitializePins(PaWinWdmFilter* filter);
bjornroche's avatar
bjornroche committed
523
static void FilterFree(PaWinWdmFilter* filter);
524 525 526 527 528 529 530 531 532 533 534 535
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);
bjornroche's avatar
bjornroche committed
536 537 538 539

/* Interface functions */
static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
static PaError IsFormatSupported(
540
struct PaUtilHostApiRepresentation *hostApi,
bjornroche's avatar
bjornroche committed
541 542 543
    const PaStreamParameters *inputParameters,
    const PaStreamParameters *outputParameters,
    double sampleRate );
544 545 546 547 548

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 );

bjornroche's avatar
bjornroche committed
549
static PaError OpenStream(
550
struct PaUtilHostApiRepresentation *hostApi,
bjornroche's avatar
bjornroche committed
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
    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(
568 569 570
                          PaStream* stream,
                          void *buffer,
                          unsigned long frames );
bjornroche's avatar
bjornroche committed
571
static PaError WriteStream(
572 573 574
                           PaStream* stream,
                           const void *buffer,
                           unsigned long frames );
bjornroche's avatar
bjornroche committed
575 576 577 578 579
static signed long GetStreamReadAvailable( PaStream* stream );
static signed long GetStreamWriteAvailable( PaStream* stream );

/* Utility functions */
static unsigned long GetWfexSize(const WAVEFORMATEX* wfex);
580
static PaWinWdmFilter** BuildFilterList(int* filterCount, int* noOfPaDevices, PaError* result);
bjornroche's avatar
bjornroche committed
581 582 583 584
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);
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
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);
bjornroche's avatar
bjornroche committed
603 604 605

/* Function bodies */

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
#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();
}

bjornroche's avatar
bjornroche committed
670 671 672 673 674 675 676 677 678 679 680 681
static unsigned long GetWfexSize(const WAVEFORMATEX* wfex)
{
    if( wfex->wFormatTag == WAVE_FORMAT_PCM )
    {
        return sizeof( WAVEFORMATEX );
    }
    else
    {
        return (sizeof( WAVEFORMATEX ) + wfex->cbSize);
    }
}

682 683 684 685 686 687 688 689 690 691
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);
}

bjornroche's avatar
bjornroche committed
692 693 694 695
/*
Low level pin/filter access functions
*/
static PaError WdmSyncIoctl(
696 697 698 699 700 701 702
                            HANDLE handle,
                            unsigned long ioctlNumber,
                            void* inBuffer,
                            unsigned long inBufferCount,
                            void* outBuffer,
                            unsigned long outBufferCount,
                            unsigned long* bytesReturned)
bjornroche's avatar
bjornroche committed
703 704
{
    PaError result = paNoError;
705 706
    unsigned long dummyBytesReturned = 0;
    BOOL bRes;
bjornroche's avatar
bjornroche committed
707 708 709

    if( !bytesReturned )
    {
710
        /* Use a dummy as the caller hasn't supplied one */
bjornroche's avatar
bjornroche committed
711 712 713
        bytesReturned = &dummyBytesReturned;
    }

714 715
    bRes = DeviceIoControl(handle, ioctlNumber, inBuffer, inBufferCount, outBuffer, outBufferCount, bytesReturned, NULL);
    if (!bRes)
bjornroche's avatar
bjornroche committed
716
    {
717 718 719 720
        unsigned long error = GetLastError();
        if ( !(((error == ERROR_INSUFFICIENT_BUFFER ) || ( error == ERROR_MORE_DATA )) && 
            ( ioctlNumber == IOCTL_KS_PROPERTY ) &&
            ( outBufferCount == 0 ) ) ) 
bjornroche's avatar
bjornroche committed
721
        {
722 723 724 725 726 727 728 729 730 731 732
            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
                );
bjornroche's avatar
bjornroche committed
733 734 735 736 737 738 739
            result = paUnanticipatedHostError;
        }
    }
    return result;
}

static PaError WdmGetPropertySimple(HANDLE handle,
740 741 742
                                    const GUID* const guidPropertySet,
                                    unsigned long property,
                                    void* value,
743
                                    unsigned long valueCount)
bjornroche's avatar
bjornroche committed
744 745
{
    PaError result;
746
    KSPROPERTY ksProperty;
bjornroche's avatar
bjornroche committed
747

748 749 750
    ksProperty.Set = *guidPropertySet;
    ksProperty.Id = property;
    ksProperty.Flags = KSPROPERTY_TYPE_GET;
bjornroche's avatar
bjornroche committed
751 752

    result = WdmSyncIoctl(
753 754
        handle,
        IOCTL_KS_PROPERTY,
755 756
        &ksProperty,
        sizeof(KSPROPERTY),
757 758 759 760
        value,
        valueCount,
        NULL);

bjornroche's avatar
bjornroche committed
761 762 763 764
    return result;
}

static PaError WdmSetPropertySimple(
765 766 767 768 769 770 771
                                    HANDLE handle,
                                    const GUID* const guidPropertySet,
                                    unsigned long property,
                                    void* value,
                                    unsigned long valueCount,
                                    void* instance,
                                    unsigned long instanceCount)
bjornroche's avatar
bjornroche committed
772 773 774 775 776 777
{
    PaError result;
    KSPROPERTY* ksProperty;
    unsigned long propertyCount  = 0;

    propertyCount = sizeof(KSPROPERTY) + instanceCount;
778
    ksProperty = (KSPROPERTY*)_alloca( propertyCount );
bjornroche's avatar
bjornroche committed
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    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(
794 795 796 797 798 799 800 801
        handle,
        IOCTL_KS_PROPERTY,
        ksProperty,
        propertyCount,
        value,
        valueCount,
        NULL);

bjornroche's avatar
bjornroche committed
802 803 804 805
    return result;
}

static PaError WdmGetPinPropertySimple(
806 807 808 809 810 811 812
                                       HANDLE  handle,
                                       unsigned long pinId,
                                       const GUID* const guidPropertySet,
                                       unsigned long property,
                                       void* value,
                                       unsigned long valueCount,
                                       unsigned long *byteCount)
bjornroche's avatar
bjornroche committed
813 814 815 816 817 818 819 820 821 822 823
{
    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(
824 825 826 827 828 829 830
        handle,
        IOCTL_KS_PROPERTY,
        &ksPProp,
        sizeof(KSP_PIN),
        value,
        valueCount,
        byteCount);
bjornroche's avatar
bjornroche committed
831 832 833 834 835

    return result;
}

static PaError WdmGetPinPropertyMulti(
836 837 838 839 840
                                      HANDLE handle,
                                      unsigned long pinId,
                                      const GUID* const guidPropertySet,
                                      unsigned long property,
                                      KSMULTIPLE_ITEM** ksMultipleItem)
bjornroche's avatar
bjornroche committed
841 842 843 844 845 846 847 848 849 850 851 852
{
    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(
853 854 855 856 857 858 859
        handle,
        IOCTL_KS_PROPERTY,
        &ksPProp.Property,
        sizeof(KSP_PIN),
        NULL,
        0,
        &multipleItemSize);
bjornroche's avatar
bjornroche committed
860 861 862 863 864 865 866 867 868 869 870 871
    if( result != paNoError )
    {
        return result;
    }

    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
    if( !*ksMultipleItem )
    {
        return paInsufficientMemory;
    }

    result = WdmSyncIoctl(
872 873 874 875 876 877 878
        handle,
        IOCTL_KS_PROPERTY,
        &ksPProp,
        sizeof(KSP_PIN),
        (void*)*ksMultipleItem,
        multipleItemSize,
        NULL);
bjornroche's avatar
bjornroche committed
879 880 881 882 883 884 885 886 887

    if( result != paNoError )
    {
        PaUtil_FreeMemory( ksMultipleItem );
    }

    return result;
}

888 889 890 891
static PaError WdmGetPropertyMulti(HANDLE handle,
                                   const GUID* const guidPropertySet,
                                   unsigned long property,
                                   KSMULTIPLE_ITEM** ksMultipleItem)
bjornroche's avatar
bjornroche committed
892 893
{
    PaError result;
894 895
    unsigned long multipleItemSize = 0;
    KSPROPERTY ksProp;
bjornroche's avatar
bjornroche committed
896

897 898 899
    ksProp.Set = *guidPropertySet;
    ksProp.Id = property;
    ksProp.Flags = KSPROPERTY_TYPE_GET;
bjornroche's avatar
bjornroche committed
900

901 902 903 904 905 906 907 908 909
    result = WdmSyncIoctl(
        handle,
        IOCTL_KS_PROPERTY,
        &ksProp,
        sizeof(KSPROPERTY),
        NULL,
        0,
        &multipleItemSize);
    if( result != paNoError )
bjornroche's avatar
bjornroche committed
910
    {
911
        return result;
bjornroche's avatar
bjornroche committed
912 913
    }

914 915
    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
    if( !*ksMultipleItem )
bjornroche's avatar
bjornroche committed
916
    {
917
        return paInsufficientMemory;
bjornroche's avatar
bjornroche committed
918 919
    }

920 921 922 923 924 925 926 927
    result = WdmSyncIoctl(
        handle,
        IOCTL_KS_PROPERTY,
        &ksProp,
        sizeof(KSPROPERTY),
        (void*)*ksMultipleItem,
        multipleItemSize,
        NULL);
bjornroche's avatar
bjornroche committed
928 929 930

    if( result != paNoError )
    {
931
        PaUtil_FreeMemory( ksMultipleItem );
bjornroche's avatar
bjornroche committed
932 933
    }

934 935
    return result;
}
bjornroche's avatar
bjornroche committed
936

937 938 939 940 941 942 943 944 945 946 947
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;
bjornroche's avatar
bjornroche committed
948

949
    result = WdmSyncIoctl(handle, IOCTL_KS_PROPERTY, &prop, sizeof(KSNODEPROPERTY), &pinId, sizeof(ULONG), NULL);
bjornroche's avatar
bjornroche committed
950

951 952
    return result;
}
bjornroche's avatar
bjornroche committed
953

954 955 956 957 958 959 960 961 962 963 964 965 966
/* 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;
bjornroche's avatar
bjornroche committed
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
        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)
bjornroche's avatar
bjornroche committed
987
    {
988 989 990 991 992
        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
        if (pConn == pTo)
            continue;

        if (pConn->ToNode == pTo->FromNode)
bjornroche's avatar
bjornroche committed
993
        {
994 995 996 997 998 999 1000 1001 1002
            if (muxIdx >= 0)
            {
                if (muxCntr < muxIdx)
                {
                    ++muxCntr;
                    continue;
                }
            }
            retval = pConn;
bjornroche's avatar
bjornroche committed
1003 1004 1005
            break;
        }
    }
1006 1007 1008
    PA_DEBUG(("GetConnectionFrom: Returning %p\n", retval));
    return retval;
}
bjornroche's avatar
bjornroche committed
1009

1010 1011 1012 1013 1014
static ULONG GetNumberOfConnectionsTo(const KSTOPOLOGY_CONNECTION* pTo, PaWinWdmFilter* filter)
{
    ULONG retval = 0;
    unsigned i;
    const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
1015
    PA_DEBUG(("GetNumberOfConnectionsTo: Checking %u connections...\n", filter->connections->Count));
1016
    for (i = 0; i < filter->connections->Count; ++i)
bjornroche's avatar
bjornroche committed
1017
    {
1018 1019 1020 1021 1022 1023
        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
        if (pConn->ToNode == pTo->FromNode &&
            (pTo->FromNode != KSFILTER_NODE || pConn->ToNodePin == pTo->FromNodePin))
        {
            ++retval;
        }
bjornroche's avatar
bjornroche committed
1024
    }
1025
    PA_DEBUG(("GetNumberOfConnectionsTo: Returning %d\n", retval));
1026 1027
    return retval;
}
bjornroche's avatar
bjornroche committed
1028

1029 1030 1031 1032 1033 1034
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);
1035
    PA_DEBUG(("FindStartConnectionFrom: Checking %u connections...\n", filter->connections->Count));
1036 1037 1038 1039 1040
    for (i = 0; i < filter->connections->Count; ++i)
    {
        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
        if (pConn->ToNode == KSFILTER_NODE && pConn->ToNodePin == startPin)
        {
1041
            PA_DEBUG(("FindStartConnectionFrom: returning %p\n", pConn));
1042 1043 1044 1045
            return pConn;
        }
    }

1046
    PA_DEBUG(("FindStartConnectionFrom: returning NULL\n"));
1047 1048 1049 1050 1051 1052 1053 1054
    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);
1055
    PA_DEBUG(("FindStartConnectionTo: Checking %u connections...\n", filter->connections->Count));
1056 1057 1058 1059 1060
    for (i = 0; i < filter->connections->Count; ++i)
    {
        const KSTOPOLOGY_CONNECTION* pConn = connections + i;
        if (pConn->FromNode == KSFILTER_NODE && pConn->FromNodePin == startPin)
        {
1061
            PA_DEBUG(("FindStartConnectionTo: returning %p\n", pConn));
1062 1063 1064 1065
            return pConn;
        }
    }

1066
    PA_DEBUG(("FindStartConnectionTo: returning NULL\n"));
1067 1068 1069 1070 1071 1072
    assert(FALSE);
    return 0;
}

static ULONG GetConnectedPin(ULONG startPin, BOOL forward, PaWinWdmFilter* filter, int muxPosition, ULONG *muxInputPinId, ULONG *muxNodeId)
{
1073
    int limit=1000;
1074 1075
    const KSTOPOLOGY_CONNECTION *conn = NULL; 
    TFnGetConnection fnGetConnection = forward ? GetConnectionTo : GetConnectionFrom ;
1076
    PA_LOGE_;
1077 1078
    while (1)
    {
1079 1080 1081 1082 1083 1084
        limit--;
        if (limit == 0) {
           PA_DEBUG(("GetConnectedPin: LOOP LIMIT REACHED\n"));
           break;
        }

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        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;
                    }
                }
            }
        }
    }
1130
    PA_LOGL_;
1131 1132 1133 1134 1135 1136 1137 1138 1139
    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);

1140
    PA_LOGE_;
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    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]
        ));
    }
1165
    PA_LOGL_;
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

}

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);

1215
    PA_LOGE_;
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    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);
    }
1255
    PA_LOGL_;
1256 1257 1258
    return result;
}

robiwan's avatar
robiwan committed
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
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;
}

robiwan's avatar
WDM-KS:  
robiwan committed
1277 1278 1279 1280 1281 1282
/* 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)
robiwan's avatar
robiwan committed
1283 1284 1285 1286 1287 1288 1289 1290 1291
{
    int i;

    for(i=0; i < defaultSampleRateSearchOrderCount; ++i)
    {
        int currentFrequency = defaultSampleRateSearchOrder[i];

        if (IsFrequencyWithinRange(range, currentFrequency))
        {
robiwan's avatar
WDM-KS:  
robiwan committed
1292
            return i;
robiwan's avatar
robiwan committed
1293 1294 1295
        }
    }

robiwan's avatar
WDM-KS:  
robiwan committed
1296
    return -1;
robiwan's avatar
robiwan committed
1297
}
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312

/*
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;
robiwan's avatar
WDM-KS:  
robiwan committed
1313
    int defaultSampleRateIndex = defaultSampleRateSearchOrderCount;
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428

    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;
bjornroche's avatar
bjornroche committed
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446

    /* 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++ )
    {
1447
        if( IsEqualGUID(&identifier[i].Set, &KSMEDIUMSETID_Standard) && ( identifier[i].Id == KSMEDIUM_STANDARD_DEVIO ) )
bjornroche's avatar
bjornroche committed
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
        {
            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;