Debian Codegraph @

external/portaudio/pa_win_wdmks.c

raw symbols SCIP
1 #ifdef _WIN32
2 /*
3 * $Id$
4 * PortAudio Windows WDM-KS interface
5 *
6 * Author: Andrew Baldwin, Robert Bielik (WaveRT)
7 * Based on the Open Source API proposed by Ross Bencina
8 * Copyright (c) 1999-2004 Andrew Baldwin, Ross Bencina, Phil Burk
9 *
10 * Permission is hereby granted, free of charge, to any person obtaining
11 * a copy of this software and associated documentation files
12 * (the "Software"), to deal in the Software without restriction,
13 * including without limitation the rights to use, copy, modify, merge,
14 * publish, distribute, sublicense, and/or sell copies of the Software,
15 * and to permit persons to whom the Software is furnished to do so,
16 * subject to the following conditions:
17 *
18 * The above copyright notice and this permission notice shall be
19 * included in all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
24 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
25 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
26 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 */
29
30 /*
31 * The text above constitutes the entire PortAudio license; however,
32 * the PortAudio community also makes the following non-binding requests:
33 *
34 * Any person wishing to distribute modifications to the Software is
35 * requested to send the modifications to the original developer so that
36 * they can be incorporated into the canonical version. It is also
37 * requested that these non-binding requests be included along with the
38 * license above.
39 */
40
41 /** @file
42 @ingroup hostapi_src
43 @brief Portaudio WDM-KS host API.
44
45 @note This is the implementation of the Portaudio host API using the
46 Windows WDM/Kernel Streaming API in order to enable very low latency
47 playback and recording on all modern Windows platforms (e.g. 2K, XP, Vista, Win7)
48 Note: This API accesses the device drivers below the usual KMIXER
49 component which is normally used to enable multi-client mixing and
50 format conversion. That means that it will lock out all other users
51 of a device for the duration of active stream using those devices
52 */
53
54 #include <stdio.h>
55
56 #if (defined(_WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
57 #pragma comment( lib, "setupapi.lib" )
58 #endif
59
60 /* Debugging/tracing support */
61
62 #define PA_LOGE_
63 #define PA_LOGL_
64
65 #ifdef __GNUC__
66 #include <initguid.h>
67 #define _WIN32_WINNT 0x0501
68 #define WINVER 0x0501
69 #endif
70
71 #include <string.h> /* strlen() */
72 #include <assert.h>
73 #include <wchar.h> /* iswspace() */
74
75 #include "pa_util.h"
76 #include "pa_allocation.h"
77 #include "pa_hostapi.h"
78 #include "pa_stream.h"
79 #include "pa_cpuload.h"
80 #include "pa_process.h"
81 #include "portaudio.h"
82 #include "pa_debugprint.h"
83 #include "pa_memorybarrier.h"
84 #include "pa_ringbuffer.h"
85 #include "pa_trace.h"
86 #include "pa_win_waveformat.h"
87
88 #include "pa_win_wdmks.h"
89
90 #ifndef DRV_QUERYDEVICEINTERFACE
91 #define DRV_QUERYDEVICEINTERFACE (DRV_RESERVED + 12)
92 #endif
93 #ifndef DRV_QUERYDEVICEINTERFACESIZE
94 #define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)
95 #endif
96
97 #include <windows.h>
98 #ifndef __GNUC__ /* Fix for ticket #257: MinGW-w64: Inclusion of <winioctl.h> triggers multiple redefinition errors. */
99 #include <winioctl.h>
100 #endif
101 #include <process.h>
102
103 #include <math.h>
104
105 #ifdef _MSC_VER
106 #define snprintf _snprintf
107 #define vsnprintf _vsnprintf
108 #endif
109
110 /* The PA_HP_TRACE macro is used in RT parts, so it can be switched off without affecting
111 the rest of the debug tracing */
112 #if 1
113 #define PA_HP_TRACE(x) PaUtil_AddHighSpeedLogMessage x ;
114 #else
115 #define PA_HP_TRACE(x)
116 #endif
117
118 /* A define that selects whether the resulting pin names are chosen from pin category
119 instead of the available pin names, who sometimes can be quite cheesy, like "Volume control".
120 Default is to use the pin category.
121 */
122 #ifndef PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES
123 #define PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES 1
124 #endif
125
126 #ifdef __GNUC__
127 #undef PA_LOGE_
128 #define PA_LOGE_ PA_DEBUG(("%s {\n",__FUNCTION__))
129 #undef PA_LOGL_
130 #define PA_LOGL_ PA_DEBUG(("} %s\n",__FUNCTION__))
131 /* These defines are set in order to allow the WIndows DirectX
132 * headers to compile with a GCC compiler such as MinGW
133 * NOTE: The headers may generate a few warning in GCC, but
134 * they should compile */
135 #define _INC_MMSYSTEM
136 #define _INC_MMREG
137 #define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */
138 #define DEFINE_GUID_THUNK(name,guid) DEFINE_GUID(name,guid)
139 #define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK( n, STATIC_##n )
140 #if !defined( DEFINE_WAVEFORMATEX_GUID )
141 #define DEFINE_WAVEFORMATEX_GUID(x) (USHORT)(x), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
142 #endif
143 #define WAVE_FORMAT_ADPCM 0x0002
144 #define WAVE_FORMAT_IEEE_FLOAT 0x0003
145 #define WAVE_FORMAT_ALAW 0x0006
146 #define WAVE_FORMAT_MULAW 0x0007
147 #define WAVE_FORMAT_MPEG 0x0050
148 #define WAVE_FORMAT_DRM 0x0009
149 #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}}
150 #define DYNAMIC_GUID(data) DYNAMIC_GUID_THUNK(data)
151 #endif
152
153 /* use CreateThread for CYGWIN/Windows Mobile, _beginthreadex for all others */
154 #if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
155 #define CREATE_THREAD_FUNCTION (HANDLE)_beginthreadex
156 #define PA_THREAD_FUNC static unsigned WINAPI
157 #else
158 #define CREATE_THREAD_FUNCTION CreateThread
159 #define PA_THREAD_FUNC static DWORD WINAPI
160 #endif
161
162 #ifdef _MSC_VER
163 #define NOMMIDS
164 #define DYNAMIC_GUID(data) {data}
165 #define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */
166 #undef DEFINE_GUID
167 #if defined(__clang__) || (defined(_MSVC_TRADITIONAL) && !_MSVC_TRADITIONAL) /* clang-cl and new msvc preprocessor: avoid too many arguments error */
168 #define DEFINE_GUID(n, ...) EXTERN_C const GUID n = {__VA_ARGS__}
169 #define DEFINE_GUID_THUNK(n, ...) DEFINE_GUID(n, __VA_ARGS__)
170 #define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK(n, STATIC_##n)
171 #else
172 #define DEFINE_GUID(n, data) EXTERN_C const GUID n = {data}
173 #define DEFINE_GUID_THUNK(n, data) DEFINE_GUID(n, data)
174 #define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK(n, STATIC_##n)
175 #endif /* __clang__, !_MSVC_TRADITIONAL */
176 #endif
177
178 #include <setupapi.h>
179
180 #ifndef EXTERN_C
181 #define EXTERN_C extern
182 #endif
183
184 #if defined(__GNUC__)
185
186 /* For MinGW we reference mingw-include files supplied with WASAPI */
187 #define WINBOOL BOOL
188
189 #include "../wasapi/mingw-include/ks.h"
190 #include "../wasapi/mingw-include/ksmedia.h"
191
192 #else
193
194 #include <mmreg.h>
195 #include <ks.h>
196
197 /* Note that Windows SDK V6.0A or later is needed for WaveRT specific structs to be present in
198 ksmedia.h. Also make sure that the SDK include path is before other include paths (that may contain
199 an "old" ksmedia.h), so the proper ksmedia.h is used */
200 #include <ksmedia.h>
201
202 #endif
203
204 #include <assert.h>
205 #include <stdio.h>
206
207 /* These next definitions allow the use of the KSUSER DLL */
208 typedef /*KSDDKAPI*/ DWORD WINAPI KSCREATEPIN(HANDLE, PKSPIN_CONNECT, ACCESS_MASK, PHANDLE);
209 extern HMODULE DllKsUser;
210 extern KSCREATEPIN* FunctionKsCreatePin;
211
212 /* These definitions allows the use of AVRT.DLL on Vista and later OSs */
213 typedef enum _PA_AVRT_PRIORITY
214 {
215 PA_AVRT_PRIORITY_LOW = -1,
216 PA_AVRT_PRIORITY_NORMAL,
217 PA_AVRT_PRIORITY_HIGH,
218 PA_AVRT_PRIORITY_CRITICAL
219 } PA_AVRT_PRIORITY, *PPA_AVRT_PRIORITY;
220
221 typedef struct
222 {
223 HINSTANCE hInstance;
224
225 HANDLE (WINAPI *AvSetMmThreadCharacteristics) (LPCSTR, LPDWORD);
226 BOOL (WINAPI *AvRevertMmThreadCharacteristics) (HANDLE);
227 BOOL (WINAPI *AvSetMmThreadPriority) (HANDLE, PA_AVRT_PRIORITY);
228 } PaWinWDMKSAvRtEntryPoints;
229
230 static PaWinWDMKSAvRtEntryPoints paWinWDMKSAvRtEntryPoints = {0};
231
232 /* An unspecified channel count (-1) is not treated correctly, so we replace it with
233 * an arbitrarily large number */
234 #define MAXIMUM_NUMBER_OF_CHANNELS 256
235
236 /* Forward definition to break circular type reference between pin and filter */
237 struct __PaWinWdmFilter;
238 typedef struct __PaWinWdmFilter PaWinWdmFilter;
239
240 struct __PaWinWdmPin;
241 typedef struct __PaWinWdmPin PaWinWdmPin;
242
243 struct __PaWinWdmStream;
244 typedef struct __PaWinWdmStream PaWinWdmStream;
245
246 /* Function prototype for getting audio position */
247 typedef PaError (*FunctionGetPinAudioPosition)(PaWinWdmPin*, unsigned long*);
248
249 /* Function prototype for memory barrier */
250 typedef void (*FunctionMemoryBarrier)(void);
251
252 struct __PaProcessThreadInfo;
253 typedef struct __PaProcessThreadInfo PaProcessThreadInfo;
254
255 typedef PaError (*FunctionPinHandler)(PaProcessThreadInfo* pInfo, unsigned eventIndex);
256
257 typedef enum __PaStreamStartEnum
258 {
259 StreamStart_kOk,
260 StreamStart_kFailed,
261 StreamStart_kCnt
262 } PaStreamStartEnum;
263
264 /* Multiplexed input structure.
265 * Very often several physical inputs are multiplexed through a MUX node (represented in the topology filter) */
266 typedef struct __PaWinWdmMuxedInput
267 {
268 wchar_t friendlyName[MAX_PATH];
269 ULONG muxPinId;
270 ULONG muxNodeId;
271 ULONG endpointPinId;
272 } PaWinWdmMuxedInput;
273
274 /* The Pin structure
275 * A pin is an input or output node, e.g. for audio flow */
276 struct __PaWinWdmPin
277 {
278 HANDLE handle;
279 PaWinWdmMuxedInput** inputs;
280 unsigned inputCount;
281 wchar_t friendlyName[MAX_PATH];
282
283 PaWinWdmFilter* parentFilter;
284 PaWDMKSSubType pinKsSubType;
285 unsigned long pinId;
286 unsigned long endpointPinId; /* For output pins */
287 KSPIN_CONNECT* pinConnect;
288 unsigned long pinConnectSize;
289 KSDATAFORMAT_WAVEFORMATEX* ksDataFormatWfx;
290 KSPIN_COMMUNICATION communication;
291 KSDATARANGE* dataRanges;
292 KSMULTIPLE_ITEM* dataRangesItem;
293 KSPIN_DATAFLOW dataFlow;
294 KSPIN_CINSTANCES instances;
295 unsigned long frameSize;
296 int maxChannels;
297 unsigned long formats;
298 int defaultSampleRate;
299 ULONG *positionRegister; /* WaveRT */
300 ULONG hwLatency; /* WaveRT */
301 FunctionMemoryBarrier fnMemBarrier; /* WaveRT */
302 FunctionGetPinAudioPosition fnAudioPosition; /* WaveRT */
303 FunctionPinHandler fnEventHandler;
304 FunctionPinHandler fnSubmitHandler;
305 };
306
307 /* The Filter structure
308 * A filter has a number of pins and a "friendly name" */
309 struct __PaWinWdmFilter
310 {
311 HANDLE handle;
312 PaWinWDMKSDeviceInfo devInfo; /* This will hold information that is exposed in PaDeviceInfo */
313
314 DWORD deviceNode;
315 int pinCount;
316 PaWinWdmPin** pins;
317 PaWinWdmFilter* topologyFilter;
318 wchar_t friendlyName[MAX_PATH];
319 int validPinCount;
320 int usageCount;
321 KSMULTIPLE_ITEM* connections;
322 KSMULTIPLE_ITEM* nodes;
323 int filterRefCount;
324 };
325
326
327 typedef struct __PaWinWdmDeviceInfo
328 {
329 PaDeviceInfo inheritedDeviceInfo;
330 char compositeName[MAX_PATH]; /* Composite name consists of pin name + device name in utf8 */
331 PaWinWdmFilter* filter;
332 unsigned long pin;
333 int muxPosition; /* Used only for input devices */
334 int endpointPinId;
335 }
336 PaWinWdmDeviceInfo;
337
338 /* PaWinWdmHostApiRepresentation - host api datastructure specific to this implementation */
339 typedef struct __PaWinWdmHostApiRepresentation
340 {
341 PaUtilHostApiRepresentation inheritedHostApiRep;
342 PaUtilStreamInterface callbackStreamInterface;
343 PaUtilStreamInterface blockingStreamInterface;
344
345 PaUtilAllocationGroup* allocations;
346 int deviceCount;
347 }
348 PaWinWdmHostApiRepresentation;
349
350 typedef struct __DATAPACKET
351 {
352 KSSTREAM_HEADER Header;
353 OVERLAPPED Signal;
354 } DATAPACKET;
355
356 typedef struct __PaIOPacket
357 {
358 DATAPACKET* packet;
359 unsigned startByte;
360 unsigned lengthBytes;
361 } PaIOPacket;
362
363 typedef struct __PaWinWdmIOInfo
364 {
365 PaWinWdmPin* pPin;
366 char* hostBuffer;
367 unsigned hostBufferSize;
368 unsigned framesPerBuffer;
369 unsigned bytesPerFrame;
370 unsigned bytesPerSample;
371 unsigned noOfPackets; /* Only used in WaveCyclic */
372 HANDLE *events; /* noOfPackets handles (WaveCyclic) 1 (WaveRT) */
373 DATAPACKET *packets; /* noOfPackets packets (WaveCyclic) 2 (WaveRT) */
374 /* WaveRT polled mode */
375 unsigned lastPosition;
376 unsigned pollCntr;
377 } PaWinWdmIOInfo;
378
379 /* PaWinWdmStream - a stream data structure specifically for this implementation */
380 struct __PaWinWdmStream
381 {
382 PaUtilStreamRepresentation streamRepresentation;
383 PaWDMKSSpecificStreamInfo hostApiStreamInfo; /* This holds info that is exposed through PaStreamInfo */
384 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
385 PaUtilBufferProcessor bufferProcessor;
386
387 #if PA_TRACE_REALTIME_EVENTS
388 LogHandle hLog;
389 #endif
390
391 PaUtilAllocationGroup* allocGroup;
392 PaWinWdmIOInfo capture;
393 PaWinWdmIOInfo render;
394 int streamStarted;
395 int streamActive;
396 int streamStop;
397 int streamAbort;
398 int oldProcessPriority;
399 HANDLE streamThread;
400 HANDLE eventAbort;
401 HANDLE eventStreamStart[StreamStart_kCnt]; /* 0 = OK, 1 = Failed */
402 PaError threadResult;
403 PaStreamFlags streamFlags;
404
405 /* Capture ring buffer */
406 PaUtilRingBuffer ringBuffer;
407 char* ringBufferData;
408
409 /* These values handle the case where the user wants to use fewer
410 * channels than the device has */
411 int userInputChannels;
412 int deviceInputChannels;
413 int userOutputChannels;
414 int deviceOutputChannels;
415 };
416
417 /* Gather all processing variables in a struct */
418 struct __PaProcessThreadInfo
419 {
420 PaWinWdmStream *stream;
421 PaStreamCallbackTimeInfo ti;
422 PaStreamCallbackFlags underover;
423 int cbResult;
424 volatile int pending;
425 volatile int priming;
426 volatile int pinsStarted;
427 unsigned long timeout;
428 unsigned captureHead;
429 unsigned captureTail;
430 unsigned renderHead;
431 unsigned renderTail;
432 PaIOPacket capturePackets[4];
433 PaIOPacket renderPackets[4];
434 };
435
436 /* Used for transferring device infos during scanning / rescanning */
437 typedef struct __PaWinWDMScanDeviceInfosResults
438 {
439 PaDeviceInfo **deviceInfos;
440 PaDeviceIndex defaultInputDevice;
441 PaDeviceIndex defaultOutputDevice;
442 } PaWinWDMScanDeviceInfosResults;
443
444 static const unsigned cPacketsArrayMask = 3;
445
446 HMODULE DllKsUser = NULL;
447 KSCREATEPIN* FunctionKsCreatePin = NULL;
448
449 /* prototypes for functions declared in this file */
450
451 #ifdef __cplusplus
452 extern "C"
453 {
454 #endif /* __cplusplus */
455
456 PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
457
458 #ifdef __cplusplus
459 }
460 #endif /* __cplusplus */
461
462 /* Low level I/O functions */
463 static PaError WdmSyncIoctl(HANDLE handle,
464 unsigned long ioctlNumber,
465 void* inBuffer,
466 unsigned long inBufferCount,
467 void* outBuffer,
468 unsigned long outBufferCount,
469 unsigned long* bytesReturned);
470
471 static PaError WdmGetPropertySimple(HANDLE handle,
472 const GUID* const guidPropertySet,
473 unsigned long property,
474 void* value,
475 unsigned long valueCount);
476
477 static PaError WdmSetPropertySimple(HANDLE handle,
478 const GUID* const guidPropertySet,
479 unsigned long property,
480 void* value,
481 unsigned long valueCount,
482 void* instance,
483 unsigned long instanceCount);
484
485 static PaError WdmGetPinPropertySimple(HANDLE handle,
486 unsigned long pinId,
487 const GUID* const guidPropertySet,
488 unsigned long property,
489 void* value,
490 unsigned long valueCount,
491 unsigned long* byteCount);
492
493 static PaError WdmGetPinPropertyMulti(HANDLE handle,
494 unsigned long pinId,
495 const GUID* const guidPropertySet,
496 unsigned long property,
497 KSMULTIPLE_ITEM** ksMultipleItem);
498
499 static PaError WdmGetPropertyMulti(HANDLE handle,
500 const GUID* const guidPropertySet,
501 unsigned long property,
502 KSMULTIPLE_ITEM** ksMultipleItem);
503
504 static PaError WdmSetMuxNodeProperty(HANDLE handle,
505 ULONG nodeId,
506 ULONG pinId);
507
508
509 /** Pin management functions */
510 static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error);
511 static void PinFree(PaWinWdmPin* pin);
512 static void PinClose(PaWinWdmPin* pin);
513 static PaError PinInstantiate(PaWinWdmPin* pin);
514 /*static PaError PinGetState(PaWinWdmPin* pin, KSSTATE* state); NOT USED */
515 static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state);
516 static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format);
517 static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format);
518 /* WaveRT support */
519 static PaError PinQueryNotificationSupport(PaWinWdmPin* pPin, BOOL* pbResult);
520 static PaError PinGetBuffer(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier);
521 static PaError PinRegisterPositionRegister(PaWinWdmPin* pPin);
522 static PaError PinRegisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle);
523 static PaError PinUnregisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle);
524 static PaError PinGetHwLatency(PaWinWdmPin* pPin, ULONG* pFifoSize, ULONG* pChipsetDelay, ULONG* pCodecDelay);
525 static PaError PinGetAudioPositionMemoryMapped(PaWinWdmPin* pPin, ULONG* pPosition);
526 static PaError PinGetAudioPositionViaIOCTLRead(PaWinWdmPin* pPin, ULONG* pPosition);
527 static PaError PinGetAudioPositionViaIOCTLWrite(PaWinWdmPin* pPin, ULONG* pPosition);
528
529 /* Filter management functions */
530 static PaWinWdmFilter* FilterNew(PaWDMKSType type, DWORD devNode, const wchar_t* filterName, const wchar_t* friendlyName, PaError* error);
531 static PaError FilterInitializePins(PaWinWdmFilter* filter);
532 static void FilterFree(PaWinWdmFilter* filter);
533 static void FilterAddRef(PaWinWdmFilter* filter);
534 static PaWinWdmPin* FilterCreatePin(
535 PaWinWdmFilter* filter,
536 int pinId,
537 const WAVEFORMATEX* wfex,
538 PaError* error);
539 static PaError FilterUse(PaWinWdmFilter* filter);
540 static void FilterRelease(PaWinWdmFilter* filter);
541
542 /* Hot plug functions */
543 static BOOL IsDeviceTheSame(const PaWinWdmDeviceInfo* pDev1,
544 const PaWinWdmDeviceInfo* pDev2);
545
546 /* Interface functions */
547 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
548 static PaError IsFormatSupported(
549 struct PaUtilHostApiRepresentation *hostApi,
550 const PaStreamParameters *inputParameters,
551 const PaStreamParameters *outputParameters,
552 double sampleRate );
553
554 static PaError ScanDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void **newDeviceInfos, int *newDeviceCount );
555 static PaError CommitDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void *deviceInfos, int deviceCount );
556 static PaError DisposeDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, void *deviceInfos, int deviceCount );
557
558 static PaError OpenStream(
559 struct PaUtilHostApiRepresentation *hostApi,
560 PaStream** s,
561 const PaStreamParameters *inputParameters,
562 const PaStreamParameters *outputParameters,
563 double sampleRate,
564 unsigned long framesPerBuffer,
565 PaStreamFlags streamFlags,
566 PaStreamCallback *streamCallback,
567 void *userData );
568 static PaError CloseStream( PaStream* stream );
569 static PaError StartStream( PaStream *stream );
570 static PaError StopStream( PaStream *stream );
571 static PaError AbortStream( PaStream *stream );
572 static PaError IsStreamStopped( PaStream *s );
573 static PaError IsStreamActive( PaStream *stream );
574 static PaTime GetStreamTime( PaStream *stream );
575 static double GetStreamCpuLoad( PaStream* stream );
576 static PaError ReadStream(
577 PaStream* stream,
578 void *buffer,
579 unsigned long frames );
580 static PaError WriteStream(
581 PaStream* stream,
582 const void *buffer,
583 unsigned long frames );
584 static signed long GetStreamReadAvailable( PaStream* stream );
585 static signed long GetStreamWriteAvailable( PaStream* stream );
586
587 /* Utility functions */
588 static unsigned long GetWfexSize(const WAVEFORMATEX* wfex);
589 static PaWinWdmFilter** BuildFilterList(int* filterCount, int* noOfPaDevices, PaError* result);
590 static BOOL PinWrite(HANDLE h, DATAPACKET* p);
591 static BOOL PinRead(HANDLE h, DATAPACKET* p);
592 static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples);
593 static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples);
594 PA_THREAD_FUNC ProcessingThread(void*);
595
596 /* Pin handler functions */
597 static PaError PaPinCaptureEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
598 static PaError PaPinCaptureSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
599
600 static PaError PaPinRenderEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
601 static PaError PaPinRenderSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex);
602
603 static PaError PaPinCaptureEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
604 static PaError PaPinCaptureEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
605 static PaError PaPinCaptureSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
606 static PaError PaPinCaptureSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
607
608 static PaError PaPinRenderEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
609 static PaError PaPinRenderEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
610 static PaError PaPinRenderSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex);
611 static PaError PaPinRenderSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex);
612
613 /* Function bodies */
614
615 #if defined(_DEBUG) && defined(PA_ENABLE_DEBUG_OUTPUT)
616 #define PA_WDMKS_SET_TREF
617 static PaTime tRef = 0;
618
619 static void PaWinWdmDebugPrintf(const char* fmt, ...)
620 {
621 va_list list;
622 char buffer[1024];
623 PaTime t = PaUtil_GetTime() - tRef;
624 va_start(list, fmt);
625 _vsnprintf(buffer, 1023, fmt, list);
626 va_end(list);
627 PaUtil_DebugPrint("%6.3lf: %s", t, buffer);
628 }
629
630 #ifdef PA_DEBUG
631 #undef PA_DEBUG
632 #define PA_DEBUG(x) PaWinWdmDebugPrintf x ;
633 #endif
634 #endif
635
636 static BOOL IsDeviceTheSame(const PaWinWdmDeviceInfo* pDev1,
637 const PaWinWdmDeviceInfo* pDev2)
638 {
639 if (pDev1 == NULL || pDev2 == NULL)
640 return FALSE;
641
642 if (pDev1 == pDev2)
643 return TRUE;
644
645 if (strcmp(pDev1->compositeName, pDev2->compositeName) == 0)
646 return TRUE;
647
648 return FALSE;
649 }
650
651 static BOOL IsEarlierThanVista()
652 {
653 /*
654 NOTE: GetVersionEx() is deprecated as of Windows 8.1 and can not be used to reliably detect
655 versions of Windows higher than Windows 8 (due to manifest requirements for reporting higher versions).
656 Microsoft recommends switching to VerifyVersionInfo (available on Win 2k and later), however GetVersionEx
657 is faster, for now we just disable the deprecation warning.
658 See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
659 See: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
660 */
661 #pragma warning (disable : 4996) /* use of GetVersionEx */
662
663 OSVERSIONINFO osvi;
664 osvi.dwOSVersionInfoSize = sizeof(osvi);
665 if (GetVersionEx(&osvi) && osvi.dwMajorVersion<6)
666 {
667 return TRUE;
668 }
669 return FALSE;
670
671 #pragma warning (default : 4996)
672 }
673
674
675
676 static void MemoryBarrierDummy(void)
677 {
678 /* Do nothing */
679 }
680
681 static void MemoryBarrierRead(void)
682 {
683 PaUtil_ReadMemoryBarrier();
684 }
685
686 static void MemoryBarrierWrite(void)
687 {
688 PaUtil_WriteMemoryBarrier();
689 }
690
691 static unsigned long GetWfexSize(const WAVEFORMATEX* wfex)
692 {
693 if( wfex->wFormatTag == WAVE_FORMAT_PCM )
694 {
695 return sizeof( WAVEFORMATEX );
696 }
697 else
698 {
699 return (sizeof( WAVEFORMATEX ) + wfex->cbSize);
700 }
701 }
702
703 static void PaWinWDM_SetLastErrorInfo(long errCode, const char* fmt, ...)
704 {
705 va_list list;
706 char buffer[1024];
707 va_start(list, fmt);
708 _vsnprintf(buffer, 1023, fmt, list);
709 va_end(list);
710 PaUtil_SetLastHostErrorInfo(paWDMKS, errCode, buffer);
711 }
712
713 /*
714 Low level pin/filter access functions
715 */
716 static PaError WdmSyncIoctl(
717 HANDLE handle,
718 unsigned long ioctlNumber,
719 void* inBuffer,
720 unsigned long inBufferCount,
721 void* outBuffer,
722 unsigned long outBufferCount,
723 unsigned long* bytesReturned)
724 {
725 PaError result = paNoError;
726 unsigned long dummyBytesReturned = 0;
727 BOOL bRes;
728
729 if( !bytesReturned )
730 {
731 /* Use a dummy as the caller hasn't supplied one */
732 bytesReturned = &dummyBytesReturned;
733 }
734
735 bRes = DeviceIoControl(handle, ioctlNumber, inBuffer, inBufferCount, outBuffer, outBufferCount, bytesReturned, NULL);
736 if (!bRes)
737 {
738 unsigned long error = GetLastError();
739 if ( !(((error == ERROR_INSUFFICIENT_BUFFER ) || ( error == ERROR_MORE_DATA )) &&
740 ( ioctlNumber == IOCTL_KS_PROPERTY ) &&
741 ( outBufferCount == 0 ) ) )
742 {
743 KSPROPERTY* ksProperty = (KSPROPERTY*)inBuffer;
744
745 PaWinWDM_SetLastErrorInfo(result, "WdmSyncIoctl: DeviceIoControl GLE = 0x%08X (prop_set = {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}, prop_id = %u)",
746 error,
747 ksProperty->Set.Data1, ksProperty->Set.Data2, ksProperty->Set.Data3,
748 ksProperty->Set.Data4[0], ksProperty->Set.Data4[1],
749 ksProperty->Set.Data4[2], ksProperty->Set.Data4[3],
750 ksProperty->Set.Data4[4], ksProperty->Set.Data4[5],
751 ksProperty->Set.Data4[6], ksProperty->Set.Data4[7],
752 ksProperty->Id
753 );
754 result = paUnanticipatedHostError;
755 }
756 }
757 return result;
758 }
759
760 static PaError WdmGetPropertySimple(HANDLE handle,
761 const GUID* const guidPropertySet,
762 unsigned long property,
763 void* value,
764 unsigned long valueCount)
765 {
766 PaError result;
767 KSPROPERTY ksProperty;
768
769 ksProperty.Set = *guidPropertySet;
770 ksProperty.Id = property;
771 ksProperty.Flags = KSPROPERTY_TYPE_GET;
772
773 result = WdmSyncIoctl(
774 handle,
775 IOCTL_KS_PROPERTY,
776 &ksProperty,
777 sizeof(KSPROPERTY),
778 value,
779 valueCount,
780 NULL);
781
782 return result;
783 }
784
785 static PaError WdmSetPropertySimple(
786 HANDLE handle,
787 const GUID* const guidPropertySet,
788 unsigned long property,
789 void* value,
790 unsigned long valueCount,
791 void* instance,
792 unsigned long instanceCount)
793 {
794 PaError result;
795 KSPROPERTY* ksProperty;
796 unsigned long propertyCount = 0;
797
798 propertyCount = sizeof(KSPROPERTY) + instanceCount;
799 ksProperty = (KSPROPERTY*)_alloca( propertyCount );
800 if( !ksProperty )
801 {
802 return paInsufficientMemory;
803 }
804
805 ksProperty->Set = *guidPropertySet;
806 ksProperty->Id = property;
807 ksProperty->Flags = KSPROPERTY_TYPE_SET;
808
809 if( instance )
810 {
811 memcpy((void*)((char*)ksProperty + sizeof(KSPROPERTY)), instance, instanceCount);
812 }
813
814 result = WdmSyncIoctl(
815 handle,
816 IOCTL_KS_PROPERTY,
817 ksProperty,
818 propertyCount,
819 value,
820 valueCount,
821 NULL);
822
823 return result;
824 }
825
826 static PaError WdmGetPinPropertySimple(
827 HANDLE handle,
828 unsigned long pinId,
829 const GUID* const guidPropertySet,
830 unsigned long property,
831 void* value,
832 unsigned long valueCount,
833 unsigned long *byteCount)
834 {
835 PaError result;
836
837 KSP_PIN ksPProp;
838 ksPProp.Property.Set = *guidPropertySet;
839 ksPProp.Property.Id = property;
840 ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
841 ksPProp.PinId = pinId;
842 ksPProp.Reserved = 0;
843
844 result = WdmSyncIoctl(
845 handle,
846 IOCTL_KS_PROPERTY,
847 &ksPProp,
848 sizeof(KSP_PIN),
849 value,
850 valueCount,
851 byteCount);
852
853 return result;
854 }
855
856 static PaError WdmGetPinPropertyMulti(
857 HANDLE handle,
858 unsigned long pinId,
859 const GUID* const guidPropertySet,
860 unsigned long property,
861 KSMULTIPLE_ITEM** ksMultipleItem)
862 {
863 PaError result;
864 unsigned long multipleItemSize = 0;
865 KSP_PIN ksPProp;
866
867 ksPProp.Property.Set = *guidPropertySet;
868 ksPProp.Property.Id = property;
869 ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
870 ksPProp.PinId = pinId;
871 ksPProp.Reserved = 0;
872
873 result = WdmSyncIoctl(
874 handle,
875 IOCTL_KS_PROPERTY,
876 &ksPProp.Property,
877 sizeof(KSP_PIN),
878 NULL,
879 0,
880 &multipleItemSize);
881 if( result != paNoError )
882 {
883 return result;
884 }
885
886 *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
887 if( !*ksMultipleItem )
888 {
889 return paInsufficientMemory;
890 }
891
892 result = WdmSyncIoctl(
893 handle,
894 IOCTL_KS_PROPERTY,
895 &ksPProp,
896 sizeof(KSP_PIN),
897 (void*)*ksMultipleItem,
898 multipleItemSize,
899 NULL);
900
901 if( result != paNoError )
902 {
903 PaUtil_FreeMemory( ksMultipleItem );
904 }
905
906 return result;
907 }
908
909 static PaError WdmGetPropertyMulti(HANDLE handle,
910 const GUID* const guidPropertySet,
911 unsigned long property,
912 KSMULTIPLE_ITEM** ksMultipleItem)
913 {
914 PaError result;
915 unsigned long multipleItemSize = 0;
916 KSPROPERTY ksProp;
917
918 ksProp.Set = *guidPropertySet;
919 ksProp.Id = property;
920 ksProp.Flags = KSPROPERTY_TYPE_GET;
921
922 result = WdmSyncIoctl(
923 handle,
924 IOCTL_KS_PROPERTY,
925 &ksProp,
926 sizeof(KSPROPERTY),
927 NULL,
928 0,
929 &multipleItemSize);
930 if( result != paNoError )
931 {
932 return result;
933 }
934
935 *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
936 if( !*ksMultipleItem )
937 {
938 return paInsufficientMemory;
939 }
940
941 result = WdmSyncIoctl(
942 handle,
943 IOCTL_KS_PROPERTY,
944 &ksProp,
945 sizeof(KSPROPERTY),
946 (void*)*ksMultipleItem,
947 multipleItemSize,
948 NULL);
949
950 if( result != paNoError )
951 {
952 PaUtil_FreeMemory( ksMultipleItem );
953 }
954
955 return result;
956 }
957
958 static PaError WdmSetMuxNodeProperty(HANDLE handle,
959 ULONG nodeId,
960 ULONG pinId)
961 {
962 PaError result = paNoError;
963 KSNODEPROPERTY prop;
964 prop.Property.Set = KSPROPSETID_Audio;
965 prop.Property.Id = KSPROPERTY_AUDIO_MUX_SOURCE;
966 prop.Property.Flags = KSPROPERTY_TYPE_SET | KSPROPERTY_TYPE_TOPOLOGY;
967 prop.NodeId = nodeId;
968 prop.Reserved = 0;
969
970 result = WdmSyncIoctl(handle, IOCTL_KS_PROPERTY, &prop, sizeof(KSNODEPROPERTY), &pinId, sizeof(ULONG), NULL);
971
972 return result;
973 }
974
975 /* Used when traversing topology for outputs */
976 static const KSTOPOLOGY_CONNECTION* GetConnectionTo(const KSTOPOLOGY_CONNECTION* pFrom, PaWinWdmFilter* filter, int muxIdx)
977 {
978 unsigned i;
979 const KSTOPOLOGY_CONNECTION* retval = NULL;
980 const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
981 (void)muxIdx;
982 PA_DEBUG(("GetConnectionTo: Checking %u connections... (pFrom = %p)", filter->connections->Count, pFrom));
983 for (i = 0; i < filter->connections->Count; ++i)
984 {
985 const KSTOPOLOGY_CONNECTION* pConn = connections + i;
986 if (pConn == pFrom)
987 continue;
988
989 if (pConn->FromNode == pFrom->ToNode)
990 {
991 retval = pConn;
992 break;
993 }
994 }
995 PA_DEBUG(("GetConnectionTo: Returning %p\n", retval));
996 return retval;
997 }
998
999 /* Used when traversing topology for inputs */
1000 static const KSTOPOLOGY_CONNECTION* GetConnectionFrom(const KSTOPOLOGY_CONNECTION* pTo, PaWinWdmFilter* filter, int muxIdx)
1001 {
1002 unsigned i;
1003 const KSTOPOLOGY_CONNECTION* retval = NULL;
1004 const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
1005 int muxCntr = 0;
1006 PA_DEBUG(("GetConnectionFrom: Checking %u connections... (pTo = %p)\n", filter->connections->Count, pTo));
1007 for (i = 0; i < filter->connections->Count; ++i)
1008 {
1009 const KSTOPOLOGY_CONNECTION* pConn = connections + i;
1010 if (pConn == pTo)
1011 continue;
1012
1013 if (pConn->ToNode == pTo->FromNode)
1014 {
1015 if (muxIdx >= 0)
1016 {
1017 if (muxCntr < muxIdx)
1018 {
1019 ++muxCntr;
1020 continue;
1021 }
1022 }
1023 retval = pConn;
1024 break;
1025 }
1026 }
1027 PA_DEBUG(("GetConnectionFrom: Returning %p\n", retval));
1028 return retval;
1029 }
1030
1031 static ULONG GetNumberOfConnectionsTo(const KSTOPOLOGY_CONNECTION* pTo, PaWinWdmFilter* filter)
1032 {
1033 ULONG retval = 0;
1034 unsigned i;
1035 const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
1036 PA_DEBUG(("GetNumberOfConnectionsTo: Checking %u connections...\n", filter->connections->Count));
1037 for (i = 0; i < filter->connections->Count; ++i)
1038 {
1039 const KSTOPOLOGY_CONNECTION* pConn = connections + i;
1040 if (pConn->ToNode == pTo->FromNode &&
1041 (pTo->FromNode != KSFILTER_NODE || pConn->ToNodePin == pTo->FromNodePin))
1042 {
1043 ++retval;
1044 }
1045 }
1046 PA_DEBUG(("GetNumberOfConnectionsTo: Returning %d\n", retval));
1047 return retval;
1048 }
1049
1050 typedef const KSTOPOLOGY_CONNECTION *(*TFnGetConnection)(const KSTOPOLOGY_CONNECTION*, PaWinWdmFilter*, int);
1051
1052 static const KSTOPOLOGY_CONNECTION* FindStartConnectionFrom(ULONG startPin, PaWinWdmFilter* filter)
1053 {
1054 unsigned i;
1055 const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
1056 PA_DEBUG(("FindStartConnectionFrom: Startpin %u, Checking %u connections...\n", startPin, filter->connections->Count));
1057 for (i = 0; i < filter->connections->Count; ++i)
1058 {
1059 const KSTOPOLOGY_CONNECTION* pConn = connections + i;
1060 if (pConn->ToNode == KSFILTER_NODE && pConn->ToNodePin == startPin)
1061 {
1062 PA_DEBUG(("FindStartConnectionFrom: returning %p\n", pConn));
1063 return pConn;
1064 }
1065 }
1066
1067 /* Some devices may report topologies that leave pins unconnected. This may be by design or driver installation
1068 issues. Pass the error condition back to caller. */
1069 PA_DEBUG(("FindStartConnectionFrom: returning NULL\n"));
1070 return 0;
1071 }
1072
1073 static const KSTOPOLOGY_CONNECTION* FindStartConnectionTo(ULONG startPin, PaWinWdmFilter* filter)
1074 {
1075 unsigned i;
1076 const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
1077 PA_DEBUG(("FindStartConnectionTo: Startpin %u, Checking %u connections...\n", startPin, filter->connections->Count));
1078 for (i = 0; i < filter->connections->Count; ++i)
1079 {
1080 const KSTOPOLOGY_CONNECTION* pConn = connections + i;
1081 if (pConn->FromNode == KSFILTER_NODE && pConn->FromNodePin == startPin)
1082 {
1083 PA_DEBUG(("FindStartConnectionTo: returning %p\n", pConn));
1084 return pConn;
1085 }
1086 }
1087
1088 /* Unconnected pin. Inform caller. */
1089 PA_DEBUG(("FindStartConnectionTo: returning NULL\n"));
1090 return 0;
1091 }
1092
1093 static ULONG GetConnectedPin(ULONG startPin, BOOL forward, PaWinWdmFilter* filter, int muxPosition, ULONG *muxInputPinId, ULONG *muxNodeId)
1094 {
1095 int limit=1000;
1096 const KSTOPOLOGY_CONNECTION *conn = NULL;
1097 TFnGetConnection fnGetConnection = forward ? GetConnectionTo : GetConnectionFrom ;
1098 PA_LOGE_;
1099 while (1)
1100 {
1101 limit--;
1102 if (limit == 0) {
1103 PA_DEBUG(("GetConnectedPin: LOOP LIMIT REACHED\n"));
1104 break;
1105 }
1106
1107 if (conn == NULL)
1108 {
1109 conn = forward ? FindStartConnectionTo(startPin, filter) : FindStartConnectionFrom(startPin, filter);
1110 }
1111 else
1112 {
1113 conn = fnGetConnection(conn, filter, -1);
1114 }
1115
1116 /* Handling case of erroneous connection list */
1117 if (conn == NULL)
1118 {
1119 break;
1120 }
1121
1122 if (forward ? conn->ToNode == KSFILTER_NODE : conn->FromNode == KSFILTER_NODE)
1123 {
1124 return forward ? conn->ToNodePin : conn->FromNodePin;
1125 }
1126 else
1127 {
1128 PA_DEBUG(("GetConnectedPin: count=%d, forward=%d, muxPosition=%d\n", filter->nodes->Count, forward, muxPosition));
1129 if (filter->nodes->Count > 0 && !forward && muxPosition >= 0)
1130 {
1131 const GUID* nodes = (const GUID*)(filter->nodes + 1);
1132 if (IsEqualGUID(&nodes[conn->FromNode], &KSNODETYPE_MUX))
1133 {
1134 ULONG nConn = GetNumberOfConnectionsTo(conn, filter);
1135 conn = fnGetConnection(conn, filter, muxPosition);
1136 if (conn == NULL)
1137 {
1138 break;
1139 }
1140 if (muxInputPinId != 0)
1141 {
1142 *muxInputPinId = conn->ToNodePin;
1143 }
1144 if (muxNodeId != 0)
1145 {
1146 *muxNodeId = conn->ToNode;
1147 }
1148 }
1149 }
1150 }
1151 }
1152 PA_LOGL_;
1153 return KSFILTER_NODE;
1154 }
1155
1156 static void DumpConnectionsAndNodes(PaWinWdmFilter* filter)
1157 {
1158 unsigned i;
1159 const KSTOPOLOGY_CONNECTION* connections = (const KSTOPOLOGY_CONNECTION*)(filter->connections + 1);
1160 const GUID* nodes = (const GUID*)(filter->nodes + 1);
1161
1162 PA_LOGE_;
1163 PA_DEBUG(("DumpConnectionsAndNodes: connections=%d, nodes=%d\n", filter->connections->Count, filter->nodes->Count));
1164
1165 for (i=0; i < filter->connections->Count; ++i)
1166 {
1167 const KSTOPOLOGY_CONNECTION* pConn = connections + i;
1168 PA_DEBUG((" Connection: %u - FromNode=%u,FromPin=%u -> ToNode=%u,ToPin=%u\n",
1169 i,
1170 pConn->FromNode, pConn->FromNodePin,
1171 pConn->ToNode, pConn->ToNodePin
1172 ));
1173 }
1174
1175 for (i=0; i < filter->nodes->Count; ++i)
1176 {
1177 const GUID* pConn = nodes + i;
1178 PA_DEBUG((" Node: %d - {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\n",
1179 i,
1180 pConn->Data1, pConn->Data2, pConn->Data3,
1181 pConn->Data4[0], pConn->Data4[1],
1182 pConn->Data4[2], pConn->Data4[3],
1183 pConn->Data4[4], pConn->Data4[5],
1184 pConn->Data4[6], pConn->Data4[7]
1185 ));
1186 }
1187 PA_LOGL_;
1188
1189 }
1190
1191 typedef struct __PaUsbTerminalGUIDToName
1192 {
1193 USHORT usbGUID;
1194 wchar_t name[64];
1195 } PaUsbTerminalGUIDToName;
1196
1197 static const PaUsbTerminalGUIDToName kNames[] =
1198 {
1199 /* Types copied from: http://msdn.microsoft.com/en-us/library/ff537742(v=vs.85).aspx */
1200 /* Input terminal types */
1201 { 0x0201, L"Microphone" },
1202 { 0x0202, L"Desktop Microphone" },
1203 { 0x0203, L"Personal Microphone" },
1204 { 0x0204, L"Omni Directional Microphone" },
1205 { 0x0205, L"Microphone Array" },
1206 { 0x0206, L"Processing Microphone Array" },
1207 /* Output terminal types */
1208 { 0x0301, L"Speakers" },
1209 { 0x0302, L"Headphones" },
1210 { 0x0303, L"Head Mounted Display Audio" },
1211 { 0x0304, L"Desktop Speaker" },
1212 { 0x0305, L"Room Speaker" },
1213 { 0x0306, L"Communication Speaker" },
1214 { 0x0307, L"LFE Speakers" },
1215 /* External terminal types */
1216 { 0x0601, L"Analog" },
1217 { 0x0602, L"Digital" },
1218 { 0x0603, L"Line" },
1219 { 0x0604, L"Audio" },
1220 { 0x0605, L"SPDIF" },
1221 };
1222
1223 static const unsigned kNamesCnt = sizeof(kNames)/sizeof(PaUsbTerminalGUIDToName);
1224
1225 static int PaUsbTerminalGUIDToNameCmp(const void* lhs, const void* rhs)
1226 {
1227 const PaUsbTerminalGUIDToName* pL = (const PaUsbTerminalGUIDToName*)lhs;
1228 const PaUsbTerminalGUIDToName* pR = (const PaUsbTerminalGUIDToName*)rhs;
1229 return ((int)(pL->usbGUID) - (int)(pR->usbGUID));
1230 }
1231
1232 static PaError GetNameFromCategory(const GUID* pGUID, BOOL input, wchar_t* name, unsigned length)
1233 {
1234 PaError result = paUnanticipatedHostError;
1235 USHORT usbTerminalGUID = (USHORT)(pGUID->Data1 - 0xDFF219E0);
1236
1237 PA_LOGE_;
1238 if (input && usbTerminalGUID >= 0x301 && usbTerminalGUID < 0x400)
1239 {
1240 /* Output terminal name for an input !? Set it to Line! */
1241 usbTerminalGUID = 0x603;
1242 }
1243 if (!input && usbTerminalGUID >= 0x201 && usbTerminalGUID < 0x300)
1244 {
1245 /* Input terminal name for an output !? Set it to Line! */
1246 usbTerminalGUID = 0x603;
1247 }
1248 if (usbTerminalGUID >= 0x201 && usbTerminalGUID < 0x713)
1249 {
1250 PaUsbTerminalGUIDToName s = { usbTerminalGUID };
1251 const PaUsbTerminalGUIDToName* ptr = bsearch(
1252 &s,
1253 kNames,
1254 kNamesCnt,
1255 sizeof(PaUsbTerminalGUIDToName),
1256 PaUsbTerminalGUIDToNameCmp
1257 );
1258 if (ptr != 0)
1259 {
1260 PA_DEBUG(("GetNameFromCategory: USB GUID %04X -> '%S'\n", usbTerminalGUID, ptr->name));
1261
1262 if (name != NULL && length > 0)
1263 {
1264 int n = _snwprintf(name, length, L"%s", ptr->name);
1265 if (usbTerminalGUID >= 0x601 && usbTerminalGUID < 0x700)
1266 {
1267 _snwprintf(name + n, length - n, L" %s", (input ? L"In":L"Out"));
1268 }
1269 }
1270 result = paNoError;
1271 }
1272 }
1273 else
1274 {
1275 PaWinWDM_SetLastErrorInfo(result, "GetNameFromCategory: usbTerminalGUID = %04X ", usbTerminalGUID);
1276 }
1277 PA_LOGL_;
1278 return result;
1279 }
1280
1281 static BOOL IsFrequencyWithinRange(const KSDATARANGE_AUDIO* range, int frequency)
1282 {
1283 if (frequency < (int)range->MinimumSampleFrequency)
1284 return FALSE;
1285 if (frequency > (int)range->MaximumSampleFrequency)
1286 return FALSE;
1287 return TRUE;
1288 }
1289
1290 static BOOL IsBitsWithinRange(const KSDATARANGE_AUDIO* range, int noOfBits)
1291 {
1292 if (noOfBits < (int)range->MinimumBitsPerSample)
1293 return FALSE;
1294 if (noOfBits > (int)range->MaximumBitsPerSample)
1295 return FALSE;
1296 return TRUE;
1297 }
1298
1299 /* Note: Somewhat different order compared to WMME implementation, as we want to focus on fidelity first */
1300 static const int defaultSampleRateSearchOrder[] =
1301 { 44100, 48000, 88200, 96000, 192000, 32000, 24000, 22050, 16000, 12000, 11025, 9600, 8000 };
1302 static const int defaultSampleRateSearchOrderCount = sizeof(defaultSampleRateSearchOrder)/sizeof(defaultSampleRateSearchOrder[0]);
1303
1304 static int DefaultSampleFrequencyIndex(const KSDATARANGE_AUDIO* range)
1305 {
1306 int i;
1307
1308 for(i=0; i < defaultSampleRateSearchOrderCount; ++i)
1309 {
1310 int currentFrequency = defaultSampleRateSearchOrder[i];
1311
1312 if (IsFrequencyWithinRange(range, currentFrequency))
1313 {
1314 return i;
1315 }
1316 }
1317
1318 return -1;
1319 }
1320
1321 /*
1322 Create a new pin object belonging to a filter
1323 The pin object holds all the configuration information about the pin
1324 before it is opened, and then the handle of the pin after is opened
1325 */
1326 static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error)
1327 {
1328 PaWinWdmPin* pin;
1329 PaError result;
1330 unsigned long i;
1331 KSMULTIPLE_ITEM* item = NULL;
1332 KSIDENTIFIER* identifier;
1333 KSDATARANGE* dataRange;
1334 const ULONG streamingId = (parentFilter->devInfo.streamingType == Type_kWaveRT) ? KSINTERFACE_STANDARD_LOOPED_STREAMING : KSINTERFACE_STANDARD_STREAMING;
1335 int defaultSampleRateIndex = defaultSampleRateSearchOrderCount;
1336
1337 PA_LOGE_;
1338 PA_DEBUG(("PinNew: Creating pin %d:\n",pinId));
1339
1340 /* Allocate the new PIN object */
1341 pin = (PaWinWdmPin*)PaUtil_AllocateMemory( sizeof(PaWinWdmPin) );
1342 if( !pin )
1343 {
1344 result = paInsufficientMemory;
1345 goto error;
1346 }
1347
1348 /* Zero the pin object */
1349 /* memset( (void*)pin, 0, sizeof(PaWinWdmPin) ); */
1350
1351 pin->parentFilter = parentFilter;
1352 pin->pinId = pinId;
1353
1354 /* Allocate a connect structure */
1355 pin->pinConnectSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX);
1356 pin->pinConnect = (KSPIN_CONNECT*)PaUtil_AllocateMemory( pin->pinConnectSize );
1357 if( !pin->pinConnect )
1358 {
1359 result = paInsufficientMemory;
1360 goto error;
1361 }
1362
1363 /* Configure the connect structure with default values */
1364 pin->pinConnect->Interface.Set = KSINTERFACESETID_Standard;
1365 pin->pinConnect->Interface.Id = streamingId;
1366 pin->pinConnect->Interface.Flags = 0;
1367 pin->pinConnect->Medium.Set = KSMEDIUMSETID_Standard;
1368 pin->pinConnect->Medium.Id = KSMEDIUM_TYPE_ANYINSTANCE;
1369 pin->pinConnect->Medium.Flags = 0;
1370 pin->pinConnect->PinId = pinId;
1371 pin->pinConnect->PinToHandle = NULL;
1372 pin->pinConnect->Priority.PriorityClass = KSPRIORITY_NORMAL;
1373 pin->pinConnect->Priority.PrioritySubClass = 1;
1374 pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)(pin->pinConnect + 1);
1375 pin->ksDataFormatWfx->DataFormat.FormatSize = sizeof(KSDATAFORMAT_WAVEFORMATEX);
1376 pin->ksDataFormatWfx->DataFormat.Flags = 0;
1377 pin->ksDataFormatWfx->DataFormat.Reserved = 0;
1378 pin->ksDataFormatWfx->DataFormat.MajorFormat = KSDATAFORMAT_TYPE_AUDIO;
1379 pin->ksDataFormatWfx->DataFormat.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1380 pin->ksDataFormatWfx->DataFormat.Specifier = KSDATAFORMAT_SPECIFIER_WAVEFORMATEX;
1381
1382 pin->frameSize = 0; /* Unknown until we instantiate pin */
1383
1384 /* Get the COMMUNICATION property */
1385 result = WdmGetPinPropertySimple(
1386 parentFilter->handle,
1387 pinId,
1388 &KSPROPSETID_Pin,
1389 KSPROPERTY_PIN_COMMUNICATION,
1390 &pin->communication,
1391 sizeof(KSPIN_COMMUNICATION),
1392 NULL);
1393 if( result != paNoError )
1394 goto error;
1395
1396 if( /*(pin->communication != KSPIN_COMMUNICATION_SOURCE) &&*/
1397 (pin->communication != KSPIN_COMMUNICATION_SINK) &&
1398 (pin->communication != KSPIN_COMMUNICATION_BOTH) )
1399 {
1400 PA_DEBUG(("PinNew: Not source/sink\n"));
1401 result = paInvalidDevice;
1402 goto error;
1403 }
1404
1405 /* Get dataflow information */
1406 result = WdmGetPinPropertySimple(
1407 parentFilter->handle,
1408 pinId,
1409 &KSPROPSETID_Pin,
1410 KSPROPERTY_PIN_DATAFLOW,
1411 &pin->dataFlow,
1412 sizeof(KSPIN_DATAFLOW),
1413 NULL);
1414
1415 if( result != paNoError )
1416 goto error;
1417
1418 /* Get the INTERFACE property list */
1419 result = WdmGetPinPropertyMulti(
1420 parentFilter->handle,
1421 pinId,
1422 &KSPROPSETID_Pin,
1423 KSPROPERTY_PIN_INTERFACES,
1424 &item);
1425
1426 if( result != paNoError )
1427 goto error;
1428
1429 identifier = (KSIDENTIFIER*)(item+1);
1430
1431 /* Check that at least one interface is STANDARD_STREAMING */
1432 result = paUnanticipatedHostError;
1433 for( i = 0; i < item->Count; i++ )
1434 {
1435 if( IsEqualGUID(&identifier[i].Set, &KSINTERFACESETID_Standard) && ( identifier[i].Id == streamingId ) )
1436 {
1437 result = paNoError;
1438 break;
1439 }
1440 }
1441
1442 if( result != paNoError )
1443 {
1444 PA_DEBUG(("PinNew: No %s streaming\n", streamingId==KSINTERFACE_STANDARD_LOOPED_STREAMING?"looped":"standard"));
1445 goto error;
1446 }
1447
1448 /* Don't need interfaces any more */
1449 PaUtil_FreeMemory( item );
1450 item = NULL;
1451
1452 /* Get the MEDIUM properties list */
1453 result = WdmGetPinPropertyMulti(
1454 parentFilter->handle,
1455 pinId,
1456 &KSPROPSETID_Pin,
1457 KSPROPERTY_PIN_MEDIUMS,
1458 &item);
1459
1460 if( result != paNoError )
1461 goto error;
1462
1463 identifier = (KSIDENTIFIER*)(item+1); /* Not actually necessary... */
1464
1465 /* Check that at least one medium is STANDARD_DEVIO */
1466 result = paUnanticipatedHostError;
1467 for( i = 0; i < item->Count; i++ )
1468 {
1469 if( IsEqualGUID(&identifier[i].Set, &KSMEDIUMSETID_Standard) && ( identifier[i].Id == KSMEDIUM_STANDARD_DEVIO ) )
1470 {
1471 result = paNoError;
1472 break;
1473 }
1474 }
1475
1476 if( result != paNoError )
1477 {
1478 PA_DEBUG(("No standard devio\n"));
1479 goto error;
1480 }
1481 /* Don't need mediums any more */
1482 PaUtil_FreeMemory( item );
1483 item = NULL;
1484
1485 /* Get DATARANGES */
1486 result = WdmGetPinPropertyMulti(
1487 parentFilter->handle,
1488 pinId,
1489 &KSPROPSETID_Pin,
1490 KSPROPERTY_PIN_DATARANGES,
1491 &pin->dataRangesItem);
1492
1493 if( result != paNoError )
1494 goto error;
1495
1496 pin->dataRanges = (KSDATARANGE*)(pin->dataRangesItem +1);
1497
1498 /* Check that at least one datarange supports audio */
1499 result = paUnanticipatedHostError;
1500 dataRange = pin->dataRanges;
1501 pin->maxChannels = 0;
1502 pin->defaultSampleRate = 0;
1503 pin->formats = 0;
1504 PA_DEBUG(("PinNew: Checking %u no of dataranges...\n", pin->dataRangesItem->Count));
1505 for( i = 0; i < pin->dataRangesItem->Count; i++)
1506 {
1507 PA_DEBUG(("PinNew: DR major format %x\n",*(unsigned long*)(&(dataRange->MajorFormat))));
1508 /* Check that subformat is WAVEFORMATEX, PCM or WILDCARD */
1509 if( IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat) ||
1510 IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM) ||
1511 IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) ||
1512 IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_WILDCARD) ||
1513 IsEqualGUID(&dataRange->MajorFormat, &KSDATAFORMAT_TYPE_AUDIO) )
1514 {
1515 int defaultIndex;
1516 result = paNoError;
1517 /* Record the maximum possible channels with this pin */
1518 if( ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels == (ULONG) -1 )
1519 {
1520 pin->maxChannels = MAXIMUM_NUMBER_OF_CHANNELS;
1521 }
1522 else if( (int) ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels > pin->maxChannels )
1523 {
1524 pin->maxChannels = (int) ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels;
1525 }
1526 PA_DEBUG(("PinNew: MaxChannel: %d\n",pin->maxChannels));
1527
1528 /* Record the formats (bit depths) that are supported */
1529 if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 8) )
1530 {
1531 pin->formats |= paInt8;
1532 PA_DEBUG(("PinNew: Format PCM 8 bit supported\n"));
1533 }
1534 if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 16) )
1535 {
1536 pin->formats |= paInt16;
1537 PA_DEBUG(("PinNew: Format PCM 16 bit supported\n"));
1538 }
1539 if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 24) )
1540 {
1541 pin->formats |= paInt24;
1542 PA_DEBUG(("PinNew: Format PCM 24 bit supported\n"));
1543 }
1544 if( IsBitsWithinRange((KSDATARANGE_AUDIO*)dataRange, 32) )
1545 {
1546 if (IsEqualGUID(&dataRange->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1547 {
1548 pin->formats |= paFloat32;
1549 PA_DEBUG(("PinNew: Format IEEE float 32 bit supported\n"));
1550 }
1551 else
1552 {
1553 pin->formats |= paInt32;
1554 PA_DEBUG(("PinNew: Format PCM 32 bit supported\n"));
1555 }
1556 }
1557
1558 defaultIndex = DefaultSampleFrequencyIndex((KSDATARANGE_AUDIO*)dataRange);
1559 if (defaultIndex >= 0 && defaultIndex < defaultSampleRateIndex)
1560 {
1561 defaultSampleRateIndex = defaultIndex;
1562 }
1563 }
1564 dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize);
1565 }
1566
1567 if( result != paNoError )
1568 goto error;
1569
1570 /* If none of the frequencies searched for are present, there's something seriously wrong */
1571 if (defaultSampleRateIndex == defaultSampleRateSearchOrderCount)
1572 {
1573 PA_DEBUG(("PinNew: No default sample rate found, skipping pin!\n"));
1574 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "PinNew: No default sample rate found");
1575 result = paUnanticipatedHostError;
1576 goto error;
1577 }
1578
1579 /* Set the default sample rate */
1580 pin->defaultSampleRate = defaultSampleRateSearchOrder[defaultSampleRateIndex];
1581 PA_DEBUG(("PinNew: Default sample rate = %d Hz\n", pin->defaultSampleRate));
1582
1583 /* Get instance information */
1584 result = WdmGetPinPropertySimple(
1585 parentFilter->handle,
1586 pinId,
1587 &KSPROPSETID_Pin,
1588 KSPROPERTY_PIN_CINSTANCES,
1589 &pin->instances,
1590 sizeof(KSPIN_CINSTANCES),
1591 NULL);
1592
1593 if( result != paNoError )
1594 goto error;
1595
1596 /* If WaveRT, check if pin supports notification mode */
1597 if (parentFilter->devInfo.streamingType == Type_kWaveRT)
1598 {
1599 BOOL bSupportsNotification = FALSE;
1600 if (PinQueryNotificationSupport(pin, &bSupportsNotification) == paNoError)
1601 {
1602 pin->pinKsSubType = bSupportsNotification ? SubType_kNotification : SubType_kPolled;
1603 }
1604 }
1605
1606 /* Query pin name (which means we need to traverse to non IRP pin, via physical connection to topology filter pin, through
1607 its nodes to the endpoint pin, and get that ones name... phew...) */
1608 PA_DEBUG(("PinNew: Finding topology pin...\n"));
1609
1610 {
1611 ULONG topoPinId = GetConnectedPin(pinId, (pin->dataFlow == KSPIN_DATAFLOW_IN), parentFilter, -1, NULL, NULL);
1612 const wchar_t kInputName[] = L"Input";
1613 const wchar_t kOutputName[] = L"Output";
1614
1615 if (topoPinId != KSFILTER_NODE)
1616 {
1617 /* Get physical connection for topo pin */
1618 unsigned long cbBytes = 0;
1619 PA_DEBUG(("PinNew: Getting physical connection...\n"));
1620 result = WdmGetPinPropertySimple(parentFilter->handle,
1621 topoPinId,
1622 &KSPROPSETID_Pin,
1623 KSPROPERTY_PIN_PHYSICALCONNECTION,
1624 0,
1625 0,
1626 &cbBytes
1627 );
1628
1629 if (result != paNoError)
1630 {
1631 /* No physical connection -> there is no topology filter! So we get the name of the pin! */
1632 PA_DEBUG(("PinNew: No physical connection! Getting the pin name\n"));
1633 result = WdmGetPinPropertySimple(parentFilter->handle,
1634 topoPinId,
1635 &KSPROPSETID_Pin,
1636 KSPROPERTY_PIN_NAME,
1637 pin->friendlyName,
1638 MAX_PATH,
1639 NULL);
1640 if (result != paNoError)
1641 {
1642 GUID category = {0};
1643
1644 /* Get pin category information */
1645 result = WdmGetPinPropertySimple(parentFilter->handle,
1646 topoPinId,
1647 &KSPROPSETID_Pin,
1648 KSPROPERTY_PIN_CATEGORY,
1649 &category,
1650 sizeof(GUID),
1651 NULL);
1652
1653 if (result == paNoError)
1654 {
1655 result = GetNameFromCategory(&category, (pin->dataFlow == KSPIN_DATAFLOW_OUT), pin->friendlyName, MAX_PATH);
1656 }
1657 }
1658
1659 /* Make sure pin gets a name here... */
1660 if (wcslen(pin->friendlyName) == 0)
1661 {
1662 wcscpy(pin->friendlyName, (pin->dataFlow == KSPIN_DATAFLOW_IN) ? kOutputName : kInputName);
1663 #ifdef UNICODE
1664 PA_DEBUG(("PinNew: Setting pin friendly name to '%s'\n", pin->friendlyName));
1665 #else
1666 PA_DEBUG(("PinNew: Setting pin friendly name to '%S'\n", pin->friendlyName));
1667 #endif
1668 }
1669
1670 /* This is then == the endpoint pin */
1671 pin->endpointPinId = (pin->dataFlow == KSPIN_DATAFLOW_IN) ? pinId : topoPinId;
1672 }
1673 else
1674 {
1675 KSPIN_PHYSICALCONNECTION* pc = (KSPIN_PHYSICALCONNECTION*)PaUtil_AllocateMemory(cbBytes + 2);
1676 ULONG pcPin;
1677 wchar_t symbLinkName[MAX_PATH];
1678 PA_DEBUG(("PinNew: Physical connection found!\n"));
1679 if (pc == NULL)
1680 {
1681 result = paInsufficientMemory;
1682 goto error;
1683 }
1684 result = WdmGetPinPropertySimple(parentFilter->handle,
1685 topoPinId,
1686 &KSPROPSETID_Pin,
1687 KSPROPERTY_PIN_PHYSICALCONNECTION,
1688 pc,
1689 cbBytes,
1690 NULL
1691 );
1692
1693 pcPin = pc->Pin;
1694 wcsncpy(symbLinkName, pc->SymbolicLinkName, MAX_PATH);
1695 PaUtil_FreeMemory( pc );
1696
1697 if (result != paNoError)
1698 {
1699 /* Shouldn't happen, but fail if it does */
1700 PA_DEBUG(("PinNew: failed to retrieve physical connection!\n"));
1701 goto error;
1702 }
1703
1704 if (symbLinkName[1] == TEXT('?'))
1705 {
1706 symbLinkName[1] = TEXT('\\');
1707 }
1708
1709 if (pin->parentFilter->topologyFilter == NULL)
1710 {
1711 PA_DEBUG(("PinNew: Creating topology filter '%S'\n", symbLinkName));
1712
1713 pin->parentFilter->topologyFilter = FilterNew(Type_kNotUsed, 0, symbLinkName, L"", &result);
1714 if (pin->parentFilter->topologyFilter == NULL)
1715 {
1716 PA_DEBUG(("PinNew: Failed creating topology filter\n"));
1717 result = paUnanticipatedHostError;
1718 PaWinWDM_SetLastErrorInfo(result, "Failed to create topology filter '%S'", symbLinkName);
1719 goto error;
1720 }
1721
1722 /* Copy info so we have it in device info */
1723 wcsncpy(pin->parentFilter->devInfo.topologyPath, symbLinkName, MAX_PATH);
1724 }
1725 else
1726 {
1727 /* Must be the same */
1728 assert(wcscmp(symbLinkName, pin->parentFilter->topologyFilter->devInfo.filterPath) == 0);
1729 }
1730
1731 PA_DEBUG(("PinNew: Opening topology filter..."));
1732
1733 result = FilterUse(pin->parentFilter->topologyFilter);
1734 if (result == paNoError)
1735 {
1736 unsigned long endpointPinId;
1737
1738 if (pin->dataFlow == KSPIN_DATAFLOW_IN)
1739 {
1740 /* The "endpointPinId" is what WASAPI looks at for pin names */
1741 GUID category = {0};
1742
1743 PA_DEBUG(("PinNew: Checking for output endpoint pin id...\n"));
1744
1745 endpointPinId = GetConnectedPin(pcPin, TRUE, pin->parentFilter->topologyFilter, -1, NULL, NULL);
1746
1747 if (endpointPinId == KSFILTER_NODE)
1748 {
1749 result = paUnanticipatedHostError;
1750 PaWinWDM_SetLastErrorInfo(result, "Failed to get endpoint pin ID on topology filter!");
1751 goto error;
1752 }
1753
1754 PA_DEBUG(("PinNew: Found endpoint pin id %u\n", endpointPinId));
1755
1756 /* Get pin category information */
1757 result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
1758 endpointPinId,
1759 &KSPROPSETID_Pin,
1760 KSPROPERTY_PIN_CATEGORY,
1761 &category,
1762 sizeof(GUID),
1763 NULL);
1764
1765 if (result == paNoError)
1766 {
1767 #if !PA_WDMKS_USE_CATEGORY_FOR_PIN_NAMES
1768 wchar_t pinName[MAX_PATH];
1769
1770 PA_DEBUG(("PinNew: Getting pin name property..."));
1771
1772 /* Ok, try pin name also, and favor that if available */
1773 result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
1774 endpointPinId,
1775 &KSPROPSETID_Pin,
1776 KSPROPERTY_PIN_NAME,
1777 pinName,
1778 MAX_PATH,
1779 NULL);
1780
1781 if (result == paNoError && wcslen(pinName)>0)
1782 {
1783 wcsncpy(pin->friendlyName, pinName, MAX_PATH);
1784 }
1785 else
1786 #endif
1787 {
1788 result = GetNameFromCategory(&category, (pin->dataFlow == KSPIN_DATAFLOW_OUT), pin->friendlyName, MAX_PATH);
1789 }
1790 }
1791
1792 /* Make sure we get a name for the pin */
1793 if (wcslen(pin->friendlyName) == 0)
1794 {
1795 wcscpy(pin->friendlyName, kOutputName);
1796 }
1797 #ifdef UNICODE
1798 PA_DEBUG(("PinNew: Pin name '%s'\n", pin->friendlyName));
1799 #else
1800 PA_DEBUG(("PinNew: Pin name '%S'\n", pin->friendlyName));
1801 #endif
1802
1803 /* Set endpoint pin ID (this is the topology INPUT pin, since portmixer will always traverse the
1804 filter in audio streaming direction, see http://msdn.microsoft.com/en-us/library/windows/hardware/ff536331(v=vs.85).aspx
1805 for more information)
1806 */
1807 pin->endpointPinId = pcPin;
1808 }
1809 else
1810 {
1811 unsigned muxCount = 0;
1812 int muxPos = 0;
1813 /* Max 64 multiplexer inputs... sanity check :) */
1814 for (i = 0; i < 64; ++i)
1815 {
1816 ULONG muxNodeIdTest = (unsigned)-1;
1817 PA_DEBUG(("PinNew: Checking for input endpoint pin id (%d)...\n", i));
1818
1819 endpointPinId = GetConnectedPin(pcPin,
1820 FALSE,
1821 pin->parentFilter->topologyFilter,
1822 (int)i,
1823 NULL,
1824 &muxNodeIdTest);
1825
1826 if (endpointPinId == KSFILTER_NODE)
1827 {
1828 /* We're done */
1829 PA_DEBUG(("PinNew: Done with inputs.\n", endpointPinId));
1830 break;
1831 }
1832 else
1833 {
1834 /* The "endpointPinId" is what WASAPI looks at for pin names */
1835 GUID category = {0};
1836
1837 PA_DEBUG(("PinNew: Found endpoint pin id %u\n", endpointPinId));
1838
1839 /* Get pin category information */
1840 result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
1841 endpointPinId,
1842 &KSPROPSETID_Pin,
1843 KSPROPERTY_PIN_CATEGORY,
1844 &category,
1845 sizeof(GUID),
1846 NULL);
1847
1848 if (result == paNoError)
1849 {
1850 if (muxNodeIdTest == (unsigned)-1)
1851 {
1852 /* Ok, try pin name, and favor that if available */
1853 result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
1854 endpointPinId,
1855 &KSPROPSETID_Pin,
1856 KSPROPERTY_PIN_NAME,
1857 pin->friendlyName,
1858 MAX_PATH,
1859 NULL);
1860
1861 if (result != paNoError)
1862 {
1863 result = GetNameFromCategory(&category, TRUE, pin->friendlyName, MAX_PATH);
1864 }
1865 break;
1866 }
1867 else
1868 {
1869 result = GetNameFromCategory(&category, TRUE, NULL, 0);
1870
1871 if (result == paNoError)
1872 {
1873 ++muxCount;
1874 }
1875 }
1876 }
1877 else
1878 {
1879 PA_DEBUG(("PinNew: Failed to get pin category"));
1880 }
1881 }
1882 }
1883
1884 if (muxCount == 0)
1885 {
1886 pin->endpointPinId = endpointPinId;
1887 /* Make sure we get a name for the pin */
1888 if (wcslen(pin->friendlyName) == 0)
1889 {
1890 wcscpy(pin->friendlyName, kInputName);
1891 }
1892 #ifdef UNICODE
1893 PA_DEBUG(("PinNew: Input friendly name '%s'\n", pin->friendlyName));
1894 #else
1895 PA_DEBUG(("PinNew: Input friendly name '%S'\n", pin->friendlyName));
1896 #endif
1897 }
1898 else // muxCount > 0
1899 {
1900 PA_DEBUG(("PinNew: Setting up %u inputs\n", muxCount));
1901
1902 /* Now we redo the operation once known how many multiplexer positions there are */
1903 pin->inputs = (PaWinWdmMuxedInput**)PaUtil_AllocateMemory(muxCount * sizeof(PaWinWdmMuxedInput*));
1904 if (pin->inputs == NULL)
1905 {
1906 FilterRelease(pin->parentFilter->topologyFilter);
1907 result = paInsufficientMemory;
1908 goto error;
1909 }
1910 pin->inputCount = muxCount;
1911
1912 for (i = 0; i < muxCount; ++muxPos)
1913 {
1914 PA_DEBUG(("PinNew: Setting up input %u...\n", i));
1915
1916 if (pin->inputs[i] == NULL)
1917 {
1918 pin->inputs[i] = (PaWinWdmMuxedInput*)PaUtil_AllocateMemory(sizeof(PaWinWdmMuxedInput));
1919 if (pin->inputs[i] == NULL)
1920 {
1921 FilterRelease(pin->parentFilter->topologyFilter);
1922 result = paInsufficientMemory;
1923 goto error;
1924 }
1925 }
1926
1927 endpointPinId = GetConnectedPin(pcPin,
1928 FALSE,
1929 pin->parentFilter->topologyFilter,
1930 muxPos,
1931 &pin->inputs[i]->muxPinId,
1932 &pin->inputs[i]->muxNodeId);
1933
1934 if (endpointPinId != KSFILTER_NODE)
1935 {
1936 /* The "endpointPinId" is what WASAPI looks at for pin names */
1937 GUID category = {0};
1938
1939 /* Set input endpoint ID */
1940 pin->inputs[i]->endpointPinId = endpointPinId;
1941
1942 /* Get pin category information */
1943 result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
1944 endpointPinId,
1945 &KSPROPSETID_Pin,
1946 KSPROPERTY_PIN_CATEGORY,
1947 &category,
1948 sizeof(GUID),
1949 NULL);
1950
1951 if (result == paNoError)
1952 {
1953 /* Try pin name first, and if that is not defined, use category instead */
1954 result = WdmGetPinPropertySimple(pin->parentFilter->topologyFilter->handle,
1955 endpointPinId,
1956 &KSPROPSETID_Pin,
1957 KSPROPERTY_PIN_NAME,
1958 pin->inputs[i]->friendlyName,
1959 MAX_PATH,
1960 NULL);
1961
1962 if (result != paNoError)
1963 {
1964 result = GetNameFromCategory(&category, TRUE, pin->inputs[i]->friendlyName, MAX_PATH);
1965 if (result != paNoError)
1966 {
1967 /* Only specify name, let name hash in ScanDeviceInfos fix postfix enumerators */
1968 wcscpy(pin->inputs[i]->friendlyName, kInputName);
1969 }
1970 }
1971 #ifdef UNICODE
1972 PA_DEBUG(("PinNew: Input (%u) friendly name '%s'\n", i, pin->inputs[i]->friendlyName));
1973 #else
1974 PA_DEBUG(("PinNew: Input (%u) friendly name '%S'\n", i, pin->inputs[i]->friendlyName));
1975 #endif
1976 ++i;
1977 }
1978 }
1979 else
1980 {
1981 /* Unconnected pin */
1982 goto error;
1983 }
1984 }
1985 }
1986 }
1987 }
1988 }
1989 }
1990 else
1991 {
1992 PA_DEBUG(("PinNew: No topology pin id found. Bad...\n"));
1993 /* No TOPO pin id ??? This is bad. Ok, so we just say it is an input or output... */
1994 wcscpy(pin->friendlyName, (pin->dataFlow == KSPIN_DATAFLOW_IN) ? kOutputName : kInputName);
1995 }
1996 }
1997
1998 /* Release topology filter if it has been used */
1999 if (pin->parentFilter->topologyFilter && pin->parentFilter->topologyFilter->handle != NULL)
2000 {
2001 PA_DEBUG(("PinNew: Releasing topology filter...\n"));
2002 FilterRelease(pin->parentFilter->topologyFilter);
2003 }
2004
2005 /* Success */
2006 *error = paNoError;
2007 PA_DEBUG(("Pin created successfully\n"));
2008 PA_LOGL_;
2009 return pin;
2010
2011 error:
2012 PA_DEBUG(("PinNew: Error %d\n", result));
2013 /*
2014 Error cleanup
2015 */
2016
2017 if (pin->parentFilter->topologyFilter && pin->parentFilter->topologyFilter->handle != NULL)
2018 {
2019 FilterRelease(pin->parentFilter->topologyFilter);
2020 }
2021
2022 PaUtil_FreeMemory( item );
2023 PinFree(pin);
2024
2025 *error = result;
2026 PA_LOGL_;
2027 return NULL;
2028 }
2029
2030 /*
2031 Safely free all resources associated with the pin
2032 */
2033 static void PinFree(PaWinWdmPin* pin)
2034 {
2035 unsigned i;
2036 PA_LOGE_;
2037 if( pin )
2038 {
2039 PinClose(pin);
2040 if( pin->pinConnect )
2041 {
2042 PaUtil_FreeMemory( pin->pinConnect );
2043 }
2044 if( pin->dataRangesItem )
2045 {
2046 PaUtil_FreeMemory( pin->dataRangesItem );
2047 }
2048 if( pin->inputs )
2049 {
2050 for (i = 0; i < pin->inputCount; ++i)
2051 {
2052 PaUtil_FreeMemory( pin->inputs[i] );
2053 }
2054 PaUtil_FreeMemory( pin->inputs );
2055 }
2056 PaUtil_FreeMemory( pin );
2057 }
2058 PA_LOGL_;
2059 }
2060
2061 /*
2062 If the pin handle is open, close it
2063 */
2064 static void PinClose(PaWinWdmPin* pin)
2065 {
2066 PA_LOGE_;
2067 if( pin == NULL )
2068 {
2069 PA_DEBUG(("Closing NULL pin!"));
2070 PA_LOGL_;
2071 return;
2072 }
2073 if( pin->handle != NULL )
2074 {
2075 PinSetState( pin, KSSTATE_PAUSE );
2076 PinSetState( pin, KSSTATE_STOP );
2077 CloseHandle( pin->handle );
2078 pin->handle = NULL;
2079 FilterRelease(pin->parentFilter);
2080 }
2081 PA_LOGL_;
2082 }
2083
2084 /*
2085 Set the state of this (instantiated) pin
2086 */
2087 static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state)
2088 {
2089 PaError result = paNoError;
2090 KSPROPERTY prop;
2091
2092 PA_LOGE_;
2093 prop.Set = KSPROPSETID_Connection;
2094 prop.Id = KSPROPERTY_CONNECTION_STATE;
2095 prop.Flags = KSPROPERTY_TYPE_SET;
2096
2097 if( pin == NULL )
2098 return paInternalError;
2099 if( pin->handle == NULL )
2100 return paInternalError;
2101
2102 result = WdmSyncIoctl(pin->handle, IOCTL_KS_PROPERTY, &prop, sizeof(KSPROPERTY), &state, sizeof(KSSTATE), NULL);
2103
2104 PA_LOGL_;
2105 return result;
2106 }
2107
2108 static PaError PinInstantiate(PaWinWdmPin* pin)
2109 {
2110 PaError result;
2111 unsigned long createResult;
2112 KSALLOCATOR_FRAMING ksaf;
2113 KSALLOCATOR_FRAMING_EX ksafex;
2114
2115 PA_LOGE_;
2116
2117 if( pin == NULL )
2118 return paInternalError;
2119 if(!pin->pinConnect)
2120 return paInternalError;
2121
2122 FilterUse(pin->parentFilter);
2123
2124 createResult = FunctionKsCreatePin(
2125 pin->parentFilter->handle,
2126 pin->pinConnect,
2127 GENERIC_WRITE | GENERIC_READ,
2128 &pin->handle
2129 );
2130
2131 PA_DEBUG(("Pin create result = 0x%08x\n",createResult));
2132 if( createResult != ERROR_SUCCESS )
2133 {
2134 FilterRelease(pin->parentFilter);
2135 pin->handle = NULL;
2136 switch (createResult)
2137 {
2138 case ERROR_INVALID_PARAMETER:
2139 /* First case when pin actually don't support the format */
2140 return paSampleFormatNotSupported;
2141 case ERROR_BAD_COMMAND:
2142 /* Case when pin is occupied (by another application) */
2143 return paDeviceUnavailable;
2144 default:
2145 /* All other cases */
2146 return paInvalidDevice;
2147 }
2148 }
2149
2150 if (pin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
2151 {
2152 /* Framing size query only valid for WaveCyclic devices */
2153 result = WdmGetPropertySimple(
2154 pin->handle,
2155 &KSPROPSETID_Connection,
2156 KSPROPERTY_CONNECTION_ALLOCATORFRAMING,
2157 &ksaf,
2158 sizeof(ksaf));
2159
2160 if( result != paNoError )
2161 {
2162 result = WdmGetPropertySimple(
2163 pin->handle,
2164 &KSPROPSETID_Connection,
2165 KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,
2166 &ksafex,
2167 sizeof(ksafex));
2168 if( result == paNoError )
2169 {
2170 pin->frameSize = ksafex.FramingItem[0].FramingRange.Range.MinFrameSize;
2171 }
2172 }
2173 else
2174 {
2175 pin->frameSize = ksaf.FrameSize;
2176 }
2177 }
2178
2179 PA_LOGL_;
2180
2181 return paNoError;
2182 }
2183
2184 static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format)
2185 {
2186 unsigned long size;
2187 void* newConnect;
2188
2189 PA_LOGE_;
2190
2191 if( pin == NULL )
2192 return paInternalError;
2193 if( format == NULL )
2194 return paInternalError;
2195
2196 size = GetWfexSize(format) + sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX) - sizeof(WAVEFORMATEX);
2197
2198 if( pin->pinConnectSize != size )
2199 {
2200 newConnect = PaUtil_AllocateMemory( size );
2201 if( newConnect == NULL )
2202 return paInsufficientMemory;
2203 memcpy( newConnect, (void*)pin->pinConnect, min(pin->pinConnectSize,size) );
2204 PaUtil_FreeMemory( pin->pinConnect );
2205 pin->pinConnect = (KSPIN_CONNECT*)newConnect;
2206 pin->pinConnectSize = size;
2207 pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)((KSPIN_CONNECT*)newConnect + 1);
2208 pin->ksDataFormatWfx->DataFormat.FormatSize = size - sizeof(KSPIN_CONNECT);
2209 }
2210
2211 memcpy( (void*)&(pin->ksDataFormatWfx->WaveFormatEx), format, GetWfexSize(format) );
2212 pin->ksDataFormatWfx->DataFormat.SampleSize = (unsigned short)(format->nChannels * (format->wBitsPerSample / 8));
2213
2214 PA_LOGL_;
2215
2216 return paNoError;
2217 }
2218
2219 static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format)
2220 {
2221 KSDATARANGE_AUDIO* dataRange;
2222 unsigned long count;
2223 GUID guid = DYNAMIC_GUID( DEFINE_WAVEFORMATEX_GUID(format->wFormatTag) );
2224 PaError result = paInvalidDevice;
2225 const WAVEFORMATEXTENSIBLE* pFormatExt = (format->wFormatTag == WAVE_FORMAT_EXTENSIBLE) ? (const WAVEFORMATEXTENSIBLE*)format : 0;
2226
2227 PA_LOGE_;
2228
2229 if( pFormatExt != 0 )
2230 {
2231 guid = pFormatExt->SubFormat;
2232 }
2233 dataRange = (KSDATARANGE_AUDIO*)pin->dataRanges;
2234 for(count = 0;
2235 count<pin->dataRangesItem->Count;
2236 count++,
2237 dataRange = (KSDATARANGE_AUDIO*)( ((char*)dataRange) + dataRange->DataRange.FormatSize)) /* Need to update dataRange here, due to 'continue' !! */
2238 {
2239 /* Check major format*/
2240 if (!(IsEqualGUID(&(dataRange->DataRange.MajorFormat), &KSDATAFORMAT_TYPE_AUDIO) ||
2241 IsEqualGUID(&(dataRange->DataRange.MajorFormat), &KSDATAFORMAT_TYPE_WILDCARD)))
2242 {
2243 continue;
2244 }
2245
2246 /* This is an audio or wildcard datarange... */
2247 if (! (IsEqualGUID(&(dataRange->DataRange.SubFormat), &KSDATAFORMAT_SUBTYPE_WILDCARD) ||
2248 IsEqualGUID(&(dataRange->DataRange.SubFormat), &KSDATAFORMAT_SUBTYPE_PCM) ||
2249 IsEqualGUID(&(dataRange->DataRange.SubFormat), &guid) ))
2250 {
2251 continue;
2252 }
2253
2254 /* Check specifier... */
2255 if (! (IsEqualGUID(&(dataRange->DataRange.Specifier), &KSDATAFORMAT_SPECIFIER_WILDCARD) ||
2256 IsEqualGUID(&(dataRange->DataRange.Specifier), &KSDATAFORMAT_SPECIFIER_WAVEFORMATEX)) )
2257 {
2258 continue;
2259 }
2260
2261 PA_DEBUG(("Pin:%x, DataRange:%d\n",(void*)pin,count));
2262 PA_DEBUG(("\tFormatSize:%d, SampleSize:%d\n",dataRange->DataRange.FormatSize,dataRange->DataRange.SampleSize));
2263 PA_DEBUG(("\tMaxChannels:%d\n",dataRange->MaximumChannels));
2264 PA_DEBUG(("\tBits:%d-%d\n",dataRange->MinimumBitsPerSample,dataRange->MaximumBitsPerSample));
2265 PA_DEBUG(("\tSampleRate:%d-%d\n",dataRange->MinimumSampleFrequency,dataRange->MaximumSampleFrequency));
2266
2267 if( dataRange->MaximumChannels != (ULONG)-1 &&
2268 dataRange->MaximumChannels < format->nChannels )
2269 {
2270 result = paInvalidChannelCount;
2271 continue;
2272 }
2273
2274 if (pFormatExt != 0)
2275 {
2276 if (!IsBitsWithinRange(dataRange, pFormatExt->Samples.wValidBitsPerSample))
2277 {
2278 result = paSampleFormatNotSupported;
2279 continue;
2280 }
2281 }
2282 else
2283 {
2284 if (!IsBitsWithinRange(dataRange, format->wBitsPerSample))
2285 {
2286 result = paSampleFormatNotSupported;
2287 continue;
2288 }
2289 }
2290
2291 if (!IsFrequencyWithinRange(dataRange, format->nSamplesPerSec))
2292 {
2293 result = paInvalidSampleRate;
2294 continue;
2295 }
2296
2297 /* Success! */
2298 result = paNoError;
2299 break;
2300 }
2301
2302 PA_LOGL_;
2303 return result;
2304 }
2305
2306 static PaError PinQueryNotificationSupport(PaWinWdmPin* pPin, BOOL* pbResult)
2307 {
2308 PaError result = paNoError;
2309 KSPROPERTY propIn;
2310
2311 PA_LOGE_;
2312
2313 propIn.Set = KSPROPSETID_RtAudio;
2314 propIn.Id = 8; /* = KSPROPERTY_RTAUDIO_QUERY_NOTIFICATION_SUPPORT */
2315 propIn.Flags = KSPROPERTY_TYPE_GET;
2316
2317 result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
2318 &propIn,
2319 sizeof(KSPROPERTY),
2320 pbResult,
2321 sizeof(BOOL),
2322 NULL);
2323
2324 if (result != paNoError)
2325 {
2326 PA_DEBUG(("Failed PinQueryNotificationSupport\n"));
2327 }
2328
2329 PA_LOGL_;
2330 return result;
2331 }
2332
2333 static PaError PinGetBufferWithNotification(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)
2334 {
2335 PaError result = paNoError;
2336 KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION propIn;
2337 KSRTAUDIO_BUFFER propOut;
2338
2339 PA_LOGE_;
2340
2341 propIn.BaseAddress = 0;
2342 propIn.NotificationCount = 2;
2343 propIn.RequestedBufferSize = *pRequestedBufSize;
2344 propIn.Property.Set = KSPROPSETID_RtAudio;
2345 propIn.Property.Id = KSPROPERTY_RTAUDIO_BUFFER_WITH_NOTIFICATION;
2346 propIn.Property.Flags = KSPROPERTY_TYPE_GET;
2347
2348 result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
2349 &propIn,
2350 sizeof(KSRTAUDIO_BUFFER_PROPERTY_WITH_NOTIFICATION),
2351 &propOut,
2352 sizeof(KSRTAUDIO_BUFFER),
2353 NULL);
2354
2355 if (result == paNoError)
2356 {
2357 *pBuffer = propOut.BufferAddress;
2358 *pRequestedBufSize = propOut.ActualBufferSize;
2359 *pbCallMemBarrier = propOut.CallMemoryBarrier;
2360 }
2361 else
2362 {
2363 PA_DEBUG(("Failed to get buffer with notification\n"));
2364 }
2365
2366 PA_LOGL_;
2367 return result;
2368 }
2369
2370 static PaError PinGetBufferWithoutNotification(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)
2371 {
2372 PaError result = paNoError;
2373 KSRTAUDIO_BUFFER_PROPERTY propIn;
2374 KSRTAUDIO_BUFFER propOut;
2375
2376 PA_LOGE_;
2377
2378 propIn.BaseAddress = NULL;
2379 propIn.RequestedBufferSize = *pRequestedBufSize;
2380 propIn.Property.Set = KSPROPSETID_RtAudio;
2381 propIn.Property.Id = KSPROPERTY_RTAUDIO_BUFFER;
2382 propIn.Property.Flags = KSPROPERTY_TYPE_GET;
2383
2384 result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
2385 &propIn,
2386 sizeof(KSRTAUDIO_BUFFER_PROPERTY),
2387 &propOut,
2388 sizeof(KSRTAUDIO_BUFFER),
2389 NULL);
2390
2391 if (result == paNoError)
2392 {
2393 *pBuffer = propOut.BufferAddress;
2394 *pRequestedBufSize = propOut.ActualBufferSize;
2395 *pbCallMemBarrier = propOut.CallMemoryBarrier;
2396 }
2397 else
2398 {
2399 PA_DEBUG(("Failed to get buffer without notification\n"));
2400 }
2401
2402 PA_LOGL_;
2403 return result;
2404 }
2405
2406 /* greatest common divisor - PGCD in French */
2407 static unsigned long PaWinWDMGCD( unsigned long a, unsigned long b )
2408 {
2409 return (b==0) ? a : PaWinWDMGCD( b, a%b);
2410 }
2411
2412
2413 /* This function will handle getting the cyclic buffer from a WaveRT driver. Certain WaveRT drivers needs to have
2414 requested buffer size on multiples of 128 bytes:
2415
2416 */
2417 static PaError PinGetBuffer(PaWinWdmPin* pPin, void** pBuffer, DWORD* pRequestedBufSize, BOOL* pbCallMemBarrier)
2418 {
2419 PaError result = paNoError;
2420 int limit = 1000;
2421 PA_LOGE_;
2422
2423 while (1)
2424 {
2425 limit--;
2426 if (limit == 0) {
2427 PA_DEBUG(("PinGetBuffer: LOOP LIMIT REACHED\n"));
2428 break;
2429 }
2430
2431 if (pPin->pinKsSubType != SubType_kPolled)
2432 {
2433 /* In case of unknown (or notification), we try both modes */
2434 result = PinGetBufferWithNotification(pPin, pBuffer, pRequestedBufSize, pbCallMemBarrier);
2435 if (result == paNoError)
2436 {
2437 PA_DEBUG(("PinGetBuffer: SubType_kNotification\n"));
2438 pPin->pinKsSubType = SubType_kNotification;
2439 break;
2440 }
2441 }
2442
2443 result = PinGetBufferWithoutNotification(pPin, pBuffer, pRequestedBufSize, pbCallMemBarrier);
2444 if (result == paNoError)
2445 {
2446 PA_DEBUG(("PinGetBuffer: SubType_kPolled\n"));
2447 pPin->pinKsSubType = SubType_kPolled;
2448 break;
2449 }
2450
2451 /* Check if requested size is on a 128 byte boundary */
2452 if (((*pRequestedBufSize) % 128UL) == 0)
2453 {
2454 PA_DEBUG(("Buffer size on 128 byte boundary, still fails :(\n"));
2455 /* Ok, can't do much more */
2456 break;
2457 }
2458 else
2459 {
2460 /* Compute LCM so we know which sizes are on a 128 byte boundary */
2461 const unsigned gcd = PaWinWDMGCD(128UL, pPin->ksDataFormatWfx->WaveFormatEx.nBlockAlign);
2462 const unsigned lcm = (128UL * pPin->ksDataFormatWfx->WaveFormatEx.nBlockAlign) / gcd;
2463 DWORD dwOldSize = *pRequestedBufSize;
2464
2465 /* Align size to (next larger) LCM byte boundary, and then we try again. Note that LCM is not necessarily a
2466 power of 2. */
2467 *pRequestedBufSize = ((*pRequestedBufSize + lcm - 1) / lcm) * lcm;
2468
2469 PA_DEBUG(("Adjusting buffer size from %u to %u bytes (128 byte boundary, LCM=%u)\n", dwOldSize, *pRequestedBufSize, lcm));
2470 }
2471 }
2472
2473 PA_LOGL_;
2474
2475 return result;
2476 }
2477
2478 static PaError PinRegisterPositionRegister(PaWinWdmPin* pPin)
2479 {
2480 PaError result = paNoError;
2481 KSRTAUDIO_HWREGISTER_PROPERTY propIn;
2482 KSRTAUDIO_HWREGISTER propOut;
2483
2484 PA_LOGE_;
2485
2486 propIn.BaseAddress = NULL;
2487 propIn.Property.Set = KSPROPSETID_RtAudio;
2488 propIn.Property.Id = KSPROPERTY_RTAUDIO_POSITIONREGISTER;
2489 propIn.Property.Flags = KSPROPERTY_TYPE_SET;
2490
2491 result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
2492 &propIn,
2493 sizeof(KSRTAUDIO_HWREGISTER_PROPERTY),
2494 &propOut,
2495 sizeof(KSRTAUDIO_HWREGISTER),
2496 NULL);
2497
2498 if (result == paNoError)
2499 {
2500 pPin->positionRegister = (ULONG*)propOut.Register;
2501 }
2502 else
2503 {
2504 PA_DEBUG(("Failed to register position register\n"));
2505 }
2506
2507 PA_LOGL_;
2508
2509 return result;
2510 }
2511
2512 static PaError PinRegisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle)
2513 {
2514 PaError result = paNoError;
2515 KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY prop;
2516
2517 PA_LOGE_;
2518
2519 prop.NotificationEvent = handle;
2520 prop.Property.Set = KSPROPSETID_RtAudio;
2521 prop.Property.Id = KSPROPERTY_RTAUDIO_REGISTER_NOTIFICATION_EVENT;
2522 prop.Property.Flags = KSPROPERTY_TYPE_SET;
2523
2524 result = WdmSyncIoctl(pPin->handle,
2525 IOCTL_KS_PROPERTY,
2526 &prop,
2527 sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
2528 &prop,
2529 sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
2530 NULL);
2531
2532 if (result != paNoError) {
2533 PA_DEBUG(("Failed to register notification handle 0x%08X\n", handle));
2534 }
2535
2536 PA_LOGL_;
2537
2538 return result;
2539 }
2540
2541 static PaError PinUnregisterNotificationHandle(PaWinWdmPin* pPin, HANDLE handle)
2542 {
2543 PaError result = paNoError;
2544 KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY prop;
2545
2546 PA_LOGE_;
2547
2548 if (handle != NULL)
2549 {
2550 prop.NotificationEvent = handle;
2551 prop.Property.Set = KSPROPSETID_RtAudio;
2552 prop.Property.Id = KSPROPERTY_RTAUDIO_UNREGISTER_NOTIFICATION_EVENT;
2553 prop.Property.Flags = KSPROPERTY_TYPE_SET;
2554
2555 result = WdmSyncIoctl(pPin->handle,
2556 IOCTL_KS_PROPERTY,
2557 &prop,
2558 sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
2559 &prop,
2560 sizeof(KSRTAUDIO_NOTIFICATION_EVENT_PROPERTY),
2561 NULL);
2562
2563 if (result != paNoError) {
2564 PA_DEBUG(("Failed to unregister notification handle 0x%08X\n", handle));
2565 }
2566 }
2567 PA_LOGL_;
2568
2569 return result;
2570 }
2571
2572 static PaError PinGetHwLatency(PaWinWdmPin* pPin, ULONG* pFifoSize, ULONG* pChipsetDelay, ULONG* pCodecDelay)
2573 {
2574 PaError result = paNoError;
2575 KSPROPERTY propIn;
2576 KSRTAUDIO_HWLATENCY propOut;
2577
2578 PA_LOGE_;
2579
2580 propIn.Set = KSPROPSETID_RtAudio;
2581 propIn.Id = KSPROPERTY_RTAUDIO_HWLATENCY;
2582 propIn.Flags = KSPROPERTY_TYPE_GET;
2583
2584 result = WdmSyncIoctl(pPin->handle, IOCTL_KS_PROPERTY,
2585 &propIn,
2586 sizeof(KSPROPERTY),
2587 &propOut,
2588 sizeof(KSRTAUDIO_HWLATENCY),
2589 NULL);
2590
2591 if (result == paNoError)
2592 {
2593 *pFifoSize = propOut.FifoSize;
2594 *pChipsetDelay = propOut.ChipsetDelay;
2595 *pCodecDelay = propOut.CodecDelay;
2596 }
2597 else
2598 {
2599 PA_DEBUG(("Failed to retrieve hardware FIFO size!\n"));
2600 }
2601
2602 PA_LOGL_;
2603
2604 return result;
2605 }
2606
2607 /* This one is used for WaveRT */
2608 static PaError PinGetAudioPositionMemoryMapped(PaWinWdmPin* pPin, ULONG* pPosition)
2609 {
2610 *pPosition = (*pPin->positionRegister);
2611 return paNoError;
2612 }
2613
2614 /* This one also, but in case the driver hasn't implemented memory mapped access to the position register */
2615 static PaError PinGetAudioPositionViaIOCTLRead(PaWinWdmPin* pPin, ULONG* pPosition)
2616 {
2617 PaError result = paNoError;
2618 KSPROPERTY propIn;
2619 KSAUDIO_POSITION propOut;
2620
2621 PA_LOGE_;
2622
2623 propIn.Set = KSPROPSETID_Audio;
2624 propIn.Id = KSPROPERTY_AUDIO_POSITION;
2625 propIn.Flags = KSPROPERTY_TYPE_GET;
2626
2627 result = WdmSyncIoctl(pPin->handle,
2628 IOCTL_KS_PROPERTY,
2629 &propIn, sizeof(KSPROPERTY),
2630 &propOut, sizeof(KSAUDIO_POSITION),
2631 NULL);
2632
2633 if (result == paNoError)
2634 {
2635 *pPosition = (ULONG)(propOut.PlayOffset);
2636 }
2637 else
2638 {
2639 PA_DEBUG(("Failed to get audio play position!\n"));
2640 }
2641
2642 PA_LOGL_;
2643
2644 return result;
2645
2646 }
2647
2648 /* This one also, but in case the driver hasn't implemented memory mapped access to the position register */
2649 static PaError PinGetAudioPositionViaIOCTLWrite(PaWinWdmPin* pPin, ULONG* pPosition)
2650 {
2651 PaError result = paNoError;
2652 KSPROPERTY propIn;
2653 KSAUDIO_POSITION propOut;
2654
2655 PA_LOGE_;
2656
2657 propIn.Set = KSPROPSETID_Audio;
2658 propIn.Id = KSPROPERTY_AUDIO_POSITION;
2659 propIn.Flags = KSPROPERTY_TYPE_GET;
2660
2661 result = WdmSyncIoctl(pPin->handle,
2662 IOCTL_KS_PROPERTY,
2663 &propIn, sizeof(KSPROPERTY),
2664 &propOut, sizeof(KSAUDIO_POSITION),
2665 NULL);
2666
2667 if (result == paNoError)
2668 {
2669 *pPosition = (ULONG)(propOut.WriteOffset);
2670 }
2671 else
2672 {
2673 PA_DEBUG(("Failed to get audio write position!\n"));
2674 }
2675
2676 PA_LOGL_;
2677
2678 return result;
2679
2680 }
2681
2682 /***********************************************************************************************/
2683
2684 /**
2685 * Create a new filter object.
2686 */
2687 static PaWinWdmFilter* FilterNew( PaWDMKSType type, DWORD devNode, const wchar_t* filterName, const wchar_t* friendlyName, PaError* error )
2688 {
2689 PaWinWdmFilter* filter = 0;
2690 PaError result;
2691
2692 /* Allocate the new filter object */
2693 filter = (PaWinWdmFilter*)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter) );
2694 if( !filter )
2695 {
2696 result = paInsufficientMemory;
2697 goto error;
2698 }
2699
2700 PA_DEBUG(("FilterNew: Creating filter '%S'\n", friendlyName));
2701
2702 /* Set type flag */
2703 filter->devInfo.streamingType = type;
2704
2705 /* Store device node */
2706 filter->deviceNode = devNode;
2707
2708 /* Zero the filter object - done by AllocateMemory */
2709 /* memset( (void*)filter, 0, sizeof(PaWinWdmFilter) ); */
2710
2711 /* Copy the filter name */
2712 wcsncpy(filter->devInfo.filterPath, filterName, MAX_PATH);
2713
2714 /* Copy the friendly name */
2715 wcsncpy(filter->friendlyName, friendlyName, MAX_PATH);
2716
2717 PA_DEBUG(("FilterNew: Opening filter...\n", friendlyName));
2718
2719 /* Open the filter handle */
2720 result = FilterUse(filter);
2721 if( result != paNoError )
2722 {
2723 goto error;
2724 }
2725
2726 /* Get pin count */
2727 result = WdmGetPinPropertySimple
2728 (
2729 filter->handle,
2730 0,
2731 &KSPROPSETID_Pin,
2732 KSPROPERTY_PIN_CTYPES,
2733 &filter->pinCount,
2734 sizeof(filter->pinCount),
2735 NULL);
2736
2737 if( result != paNoError)
2738 {
2739 goto error;
2740 }
2741
2742 /* Get connections & nodes for filter */
2743 result = WdmGetPropertyMulti(
2744 filter->handle,
2745 &KSPROPSETID_Topology,
2746 KSPROPERTY_TOPOLOGY_CONNECTIONS,
2747 &filter->connections);
2748
2749 if( result != paNoError)
2750 {
2751 goto error;
2752 }
2753
2754 result = WdmGetPropertyMulti(
2755 filter->handle,
2756 &KSPROPSETID_Topology,
2757 KSPROPERTY_TOPOLOGY_NODES,
2758 &filter->nodes);
2759
2760 if( result != paNoError)
2761 {
2762 goto error;
2763 }
2764
2765 /* For debugging purposes */
2766 DumpConnectionsAndNodes(filter);
2767
2768 /* Get product GUID (it might not be supported) */
2769 {
2770 KSCOMPONENTID compId;
2771 if (WdmGetPropertySimple(filter->handle, &KSPROPSETID_General, KSPROPERTY_GENERAL_COMPONENTID, &compId, sizeof(KSCOMPONENTID)) == paNoError)
2772 {
2773 filter->devInfo.deviceProductGuid = compId.Product;
2774 }
2775 }
2776
2777 /* This section is not executed for topology filters */
2778 if (type != Type_kNotUsed)
2779 {
2780 /* Initialize the pins */
2781 result = FilterInitializePins(filter);
2782
2783 if( result != paNoError)
2784 {
2785 goto error;
2786 }
2787 }
2788
2789 /* Close the filter handle for now
2790 * It will be opened later when needed */
2791 FilterRelease(filter);
2792
2793 *error = paNoError;
2794 return filter;
2795
2796 error:
2797 PA_DEBUG(("FilterNew: Error %d\n", result));
2798 /*
2799 Error cleanup
2800 */
2801 FilterFree(filter);
2802
2803 *error = result;
2804 return NULL;
2805 }
2806
2807 /**
2808 * Add reference to filter
2809 */
2810 static void FilterAddRef( PaWinWdmFilter* filter )
2811 {
2812 if (filter != 0)
2813 {
2814 filter->filterRefCount++;
2815 }
2816 }
2817
2818
2819 /**
2820 * Initialize the pins of the filter. This is separated from FilterNew because this might fail if there is another
2821 * process using the pin(s).
2822 */
2823 PaError FilterInitializePins( PaWinWdmFilter* filter )
2824 {
2825 PaError result = paNoError;
2826 int pinId;
2827
2828 if (filter->devInfo.streamingType == Type_kNotUsed)
2829 return paNoError;
2830
2831 if (filter->pins != NULL)
2832 return paNoError;
2833
2834 /* Allocate pointer array to hold the pins */
2835 filter->pins = (PaWinWdmPin**)PaUtil_AllocateMemory( sizeof(PaWinWdmPin*) * filter->pinCount );
2836 if( !filter->pins )
2837 {
2838 result = paInsufficientMemory;
2839 goto error;
2840 }
2841
2842 /* Create all the pins we can */
2843 for(pinId = 0; pinId < filter->pinCount; pinId++)
2844 {
2845 /* Create the pin with this Id */
2846 PaWinWdmPin* newPin;
2847 newPin = PinNew(filter, pinId, &result);
2848 if( result == paInsufficientMemory )
2849 goto error;
2850 if( newPin != NULL )
2851 {
2852 filter->pins[pinId] = newPin;
2853 ++filter->validPinCount;
2854 }
2855 else
2856 {
2857 filter->pins[pinId] = 0;
2858 }
2859 }
2860
2861 if (filter->validPinCount == 0)
2862 {
2863 result = paDeviceUnavailable;
2864 goto error;
2865 }
2866
2867 return paNoError;
2868
2869 error:
2870
2871 if (filter->pins)
2872 {
2873 for (pinId = 0; pinId < filter->pinCount; ++pinId)
2874 {
2875 if (filter->pins[pinId])
2876 {
2877 PinFree(filter->pins[pinId]);
2878 filter->pins[pinId] = 0;
2879 }
2880 }
2881 PaUtil_FreeMemory( filter->pins );
2882 filter->pins = 0;
2883 }
2884
2885 return result;
2886 }
2887
2888
2889 /**
2890 * Free a previously created filter
2891 */
2892 static void FilterFree(PaWinWdmFilter* filter)
2893 {
2894 PA_LOGL_;
2895 if( filter )
2896 {
2897 if (--filter->filterRefCount > 0)
2898 {
2899 /* Ok, a stream has a ref count to this filter */
2900 return;
2901 }
2902
2903 if ( filter->topologyFilter )
2904 {
2905 FilterFree(filter->topologyFilter);
2906 filter->topologyFilter = 0;
2907 }
2908 if ( filter->pins )
2909 {
2910 int pinId;
2911 for( pinId = 0; pinId < filter->pinCount; pinId++ )
2912 PinFree(filter->pins[pinId]);
2913 PaUtil_FreeMemory( filter->pins );
2914 filter->pins = 0;
2915 }
2916 if( filter->connections )
2917 {
2918 PaUtil_FreeMemory(filter->connections);
2919 filter->connections = 0;
2920 }
2921 if( filter->nodes )
2922 {
2923 PaUtil_FreeMemory(filter->nodes);
2924 filter->nodes = 0;
2925 }
2926 if( filter->handle )
2927 CloseHandle( filter->handle );
2928 PaUtil_FreeMemory( filter );
2929 }
2930 PA_LOGE_;
2931 }
2932
2933 /**
2934 * Reopen the filter handle if necessary so it can be used
2935 **/
2936 static PaError FilterUse(PaWinWdmFilter* filter)
2937 {
2938 assert( filter );
2939
2940 PA_LOGE_;
2941 if( filter->handle == NULL )
2942 {
2943 /* Open the filter */
2944 filter->handle = CreateFileW(
2945 filter->devInfo.filterPath,
2946 GENERIC_READ | GENERIC_WRITE,
2947 0,
2948 NULL,
2949 OPEN_EXISTING,
2950 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
2951 NULL);
2952
2953 if( filter->handle == NULL )
2954 {
2955 return paDeviceUnavailable;
2956 }
2957 }
2958 filter->usageCount++;
2959 PA_LOGL_;
2960 return paNoError;
2961 }
2962
2963 /**
2964 * Release the filter handle if nobody is using it
2965 **/
2966 static void FilterRelease(PaWinWdmFilter* filter)
2967 {
2968 assert( filter );
2969 assert( filter->usageCount > 0 );
2970
2971 PA_LOGE_;
2972 /* Check first topology filter, if used */
2973 if (filter->topologyFilter != NULL && filter->topologyFilter->handle != NULL)
2974 {
2975 FilterRelease(filter->topologyFilter);
2976 }
2977
2978 filter->usageCount--;
2979 if( filter->usageCount == 0 )
2980 {
2981 if( filter->handle != NULL )
2982 {
2983 CloseHandle( filter->handle );
2984 filter->handle = NULL;
2985 }
2986 }
2987 PA_LOGL_;
2988 }
2989
2990 /**
2991 * Create a render or playback pin using the supplied format
2992 **/
2993 static PaWinWdmPin* FilterCreatePin(PaWinWdmFilter* filter,
2994 int pinId,
2995 const WAVEFORMATEX* wfex,
2996 PaError* error)
2997 {
2998 PaError result = paNoError;
2999 PaWinWdmPin* pin = NULL;
3000 assert( filter );
3001 assert( pinId < filter->pinCount );
3002 pin = filter->pins[pinId];
3003 assert( pin );
3004 result = PinSetFormat(pin,wfex);
3005 if( result == paNoError )
3006 {
3007 result = PinInstantiate(pin);
3008 }
3009 *error = result;
3010 return result == paNoError ? pin : 0;
3011 }
3012
3013 static const wchar_t kUsbPrefix[] = L"\\\\?\\USB";
3014
3015 static BOOL IsUSBDevice(const wchar_t* devicePath)
3016 {
3017 /* Alex Lessard pointed out that different devices might present the device path with
3018 lower case letters. */
3019 return (_wcsnicmp(devicePath, kUsbPrefix, sizeof(kUsbPrefix)/sizeof(kUsbPrefix[0]) ) == 0);
3020 }
3021
3022 /* This should make it more language tolerant, I hope... */
3023 static const wchar_t kUsbNamePrefix[] = L"USB Audio";
3024
3025 static BOOL IsNameUSBAudioDevice(const wchar_t* friendlyName)
3026 {
3027 return (_wcsnicmp(friendlyName, kUsbNamePrefix, sizeof(kUsbNamePrefix)/sizeof(kUsbNamePrefix[0])) == 0);
3028 }
3029
3030 typedef enum _tag_EAlias
3031 {
3032 Alias_kRender = (1<<0),
3033 Alias_kCapture = (1<<1),
3034 Alias_kRealtime = (1<<2),
3035 } EAlias;
3036
3037 /* Trim whitespace from string */
3038 static void TrimString(wchar_t* str, size_t length)
3039 {
3040 wchar_t* s = str;
3041 wchar_t* e = 0;
3042
3043 /* Find start of string */
3044 while (iswspace_portable(*s)) ++s;
3045 e=s+min(length,wcslen(s))-1;
3046
3047 /* Find end of string */
3048 while(e>s && iswspace_portable(*e)) --e;
3049 ++e;
3050
3051 length = e - s;
3052 memmove(str, s, length * sizeof(wchar_t));
3053 str[length] = 0;
3054 }
3055
3056 /**
3057 * Build the list of available filters
3058 * Use the SetupDi API to enumerate all devices in the KSCATEGORY_AUDIO which
3059 * have a KSCATEGORY_RENDER or KSCATEGORY_CAPTURE alias. For each of these
3060 * devices initialise a PaWinWdmFilter structure by calling our NewFilter()
3061 * function. We enumerate devices twice, once to count how many there are,
3062 * and once to initialize the PaWinWdmFilter structures.
3063 *
3064 * Vista and later: Also check KSCATEGORY_REALTIME for WaveRT devices.
3065 */
3066 //PaError BuildFilterList( PaWinWdmHostApiRepresentation* wdmHostApi, int* noOfPaDevices )
3067 PaWinWdmFilter** BuildFilterList( int* pFilterCount, int* pNoOfPaDevices, PaError* pResult )
3068 {
3069 PaWinWdmFilter** ppFilters = NULL;
3070 HDEVINFO handle = NULL;
3071 int device;
3072 int invalidDevices;
3073 int slot;
3074 SP_DEVICE_INTERFACE_DATA interfaceData;
3075 SP_DEVICE_INTERFACE_DATA aliasData;
3076 SP_DEVINFO_DATA devInfoData;
3077 int noError;
3078 const int sizeInterface = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR));
3079 unsigned char interfaceDetailsArray[sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR))];
3080 SP_DEVICE_INTERFACE_DETAIL_DATA_W* devInterfaceDetails = (SP_DEVICE_INTERFACE_DETAIL_DATA_W*)interfaceDetailsArray;
3081 const GUID* category = (const GUID*)&KSCATEGORY_AUDIO;
3082 const GUID* alias_render = (const GUID*)&KSCATEGORY_RENDER;
3083 const GUID* alias_capture = (const GUID*)&KSCATEGORY_CAPTURE;
3084 const GUID* category_realtime = (const GUID*)&KSCATEGORY_REALTIME;
3085 DWORD aliasFlags;
3086 PaWDMKSType streamingType;
3087 int filterCount = 0;
3088 int noOfPaDevices = 0;
3089
3090 PA_LOGE_;
3091
3092 assert(pFilterCount != NULL);
3093 assert(pNoOfPaDevices != NULL);
3094 assert(pResult != NULL);
3095
3096 devInterfaceDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
3097 *pFilterCount = 0;
3098 *pNoOfPaDevices = 0;
3099
3100 /* Open a handle to search for devices (filters) */
3101 handle = SetupDiGetClassDevs(category,NULL,NULL,DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
3102 if( handle == INVALID_HANDLE_VALUE )
3103 {
3104 *pResult = paUnanticipatedHostError;
3105 return NULL;
3106 }
3107 PA_DEBUG(("Setup called\n"));
3108
3109 /* First let's count the number of devices so we can allocate a list */
3110 invalidDevices = 0;
3111 for( device = 0;;device++ )
3112 {
3113 interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
3114 interfaceData.Reserved = 0;
3115 aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
3116 aliasData.Reserved = 0;
3117 noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);
3118 PA_DEBUG(("Enum called\n"));
3119 if( !noError )
3120 break; /* No more devices */
3121
3122 /* Check this one has the render or capture alias */
3123 aliasFlags = 0;
3124 noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);
3125 PA_DEBUG(("noError = %d\n",noError));
3126 if(noError)
3127 {
3128 if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
3129 {
3130 PA_DEBUG(("Device %d has render alias\n",device));
3131 aliasFlags |= Alias_kRender; /* Has render alias */
3132 }
3133 else
3134 {
3135 PA_DEBUG(("Device %d has no render alias\n",device));
3136 }
3137 }
3138 noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);
3139 if(noError)
3140 {
3141 if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
3142 {
3143 PA_DEBUG(("Device %d has capture alias\n",device));
3144 aliasFlags |= Alias_kCapture; /* Has capture alias */
3145 }
3146 else
3147 {
3148 PA_DEBUG(("Device %d has no capture alias\n",device));
3149 }
3150 }
3151 if(!aliasFlags)
3152 invalidDevices++; /* This was not a valid capture or render audio device */
3153 }
3154 /* Remember how many there are */
3155 filterCount = device-invalidDevices;
3156
3157 PA_DEBUG(("Interfaces found: %d\n",device-invalidDevices));
3158
3159 /* Now allocate the list of pointers to devices */
3160 ppFilters = (PaWinWdmFilter**)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter*) * filterCount);
3161 if( ppFilters == 0 )
3162 {
3163 if(handle != NULL)
3164 SetupDiDestroyDeviceInfoList(handle);
3165 *pResult = paInsufficientMemory;
3166 return NULL;
3167 }
3168
3169 /* Now create filter objects for each interface found */
3170 slot = 0;
3171 for( device = 0;;device++ )
3172 {
3173 interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
3174 interfaceData.Reserved = 0;
3175 aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
3176 aliasData.Reserved = 0;
3177 devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
3178 devInfoData.Reserved = 0;
3179 streamingType = Type_kWaveCyclic;
3180
3181 noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);
3182 if( !noError )
3183 break; /* No more devices */
3184
3185 /* Check this one has the render or capture alias */
3186 aliasFlags = 0;
3187 noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);
3188 if(noError)
3189 {
3190 if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
3191 {
3192 PA_DEBUG(("Device %d has render alias\n",device));
3193 aliasFlags |= Alias_kRender; /* Has render alias */
3194 }
3195 }
3196 noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);
3197 if(noError)
3198 {
3199 if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
3200 {
3201 PA_DEBUG(("Device %d has capture alias\n",device));
3202 aliasFlags |= Alias_kCapture; /* Has capture alias */
3203 }
3204 }
3205 if(!aliasFlags)
3206 {
3207 continue; /* This was not a valid capture or render audio device */
3208 }
3209 else
3210 {
3211 /* Check if filter is WaveRT, if not it is a WaveCyclic */
3212 noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,category_realtime,&aliasData);
3213 if (noError)
3214 {
3215 PA_DEBUG(("Device %d has realtime alias\n",device));
3216 aliasFlags |= Alias_kRealtime;
3217 streamingType = Type_kWaveRT;
3218 }
3219 }
3220
3221 noError = SetupDiGetDeviceInterfaceDetailW(handle,&interfaceData,devInterfaceDetails,sizeInterface,NULL,&devInfoData);
3222 if( noError )
3223 {
3224 DWORD type;
3225 WCHAR friendlyName[MAX_PATH] = {0};
3226 DWORD sizeFriendlyName;
3227 PaWinWdmFilter* newFilter = 0;
3228
3229 PaError result = paNoError;
3230 /* Try to get the "friendly name" for this interface */
3231 sizeFriendlyName = sizeof(friendlyName);
3232
3233 if (IsEarlierThanVista() && IsUSBDevice(devInterfaceDetails->DevicePath))
3234 {
3235 /* XP and USB audio device needs to look elsewhere, otherwise it'll only be a "USB Audio Device". Not
3236 very literate. */
3237 if (!SetupDiGetDeviceRegistryPropertyW(handle,
3238 &devInfoData,
3239 SPDRP_LOCATION_INFORMATION,
3240 &type,
3241 (BYTE*)friendlyName,
3242 sizeof(friendlyName),
3243 NULL))
3244 {
3245 friendlyName[0] = 0;
3246 }
3247 }
3248
3249 if (friendlyName[0] == 0 || IsNameUSBAudioDevice(friendlyName))
3250 {
3251 /* Fix contributed by Ben Allison
3252 * Removed KEY_SET_VALUE from flags on following call
3253 * as its causes failure when running without admin rights
3254 * and it was not required */
3255 HKEY hkey=SetupDiOpenDeviceInterfaceRegKey(handle,&interfaceData,0,KEY_QUERY_VALUE);
3256 if(hkey!=INVALID_HANDLE_VALUE)
3257 {
3258 noError = RegQueryValueExW(hkey,L"FriendlyName",0,&type,(BYTE*)friendlyName,&sizeFriendlyName);
3259 if( noError == ERROR_SUCCESS )
3260 {
3261 PA_DEBUG(("Interface %d, Name: %s\n",device,friendlyName));
3262 RegCloseKey(hkey);
3263 }
3264 else
3265 {
3266 friendlyName[0] = 0;
3267 }
3268 }
3269 }
3270
3271 TrimString(friendlyName, sizeFriendlyName);
3272
3273 newFilter = FilterNew(streamingType,
3274 devInfoData.DevInst,
3275 devInterfaceDetails->DevicePath,
3276 friendlyName,
3277 &result);
3278
3279 if( result == paNoError )
3280 {
3281 int pin;
3282 unsigned filterIOs = 0;
3283
3284 /* Increment number of "devices" */
3285 for (pin = 0; pin < newFilter->pinCount; ++pin)
3286 {
3287 PaWinWdmPin* pPin = newFilter->pins[pin];
3288 if (pPin == NULL)
3289 continue;
3290
3291 filterIOs += max(1, pPin->inputCount);
3292 }
3293
3294 noOfPaDevices += filterIOs;
3295
3296 PA_DEBUG(("Filter (%s) created with %d valid pins (total I/Os: %u)\n", ((newFilter->devInfo.streamingType==Type_kWaveRT)?"WaveRT":"WaveCyclic"), newFilter->validPinCount, filterIOs));
3297
3298 assert(slot < filterCount);
3299
3300 ppFilters[slot] = newFilter;
3301
3302 slot++;
3303 }
3304 else
3305 {
3306 PA_DEBUG(("Filter NOT created\n"));
3307 /* As there are now less filters than we initially thought
3308 * we must reduce the count by one */
3309 filterCount--;
3310 }
3311 }
3312 }
3313
3314 /* Clean up */
3315 if(handle != NULL)
3316 SetupDiDestroyDeviceInfoList(handle);
3317
3318 *pFilterCount = filterCount;
3319 *pNoOfPaDevices = noOfPaDevices;
3320
3321 return ppFilters;
3322 }
3323
3324 typedef struct PaNameHashIndex
3325 {
3326 unsigned index;
3327 unsigned count;
3328 ULONG hash;
3329 struct PaNameHashIndex *next;
3330 } PaNameHashIndex;
3331
3332 typedef struct PaNameHashObject
3333 {
3334 PaNameHashIndex* list;
3335 PaUtilAllocationGroup* allocGroup;
3336 } PaNameHashObject;
3337
3338 static ULONG GetNameHash(const wchar_t* str, const BOOL input)
3339 {
3340 /* This is to make sure that a name that exists as both input & output won't get the same hash value */
3341 const ULONG fnv_prime = (input ? 0x811C9DD7 : 0x811FEB0B);
3342 ULONG hash = 0;
3343 for(; *str != 0; str++)
3344 {
3345 hash *= fnv_prime;
3346 hash ^= (*str);
3347 }
3348 assert(hash != 0);
3349 return hash;
3350 }
3351
3352 static PaError CreateHashEntry(PaNameHashObject* obj, const wchar_t* name, const BOOL input)
3353 {
3354 ULONG hash = GetNameHash(name, input);
3355 PaNameHashIndex * pLast = NULL;
3356 PaNameHashIndex * p = obj->list;
3357 while (p != 0)
3358 {
3359 if (p->hash == hash)
3360 {
3361 break;
3362 }
3363 pLast = p;
3364 p = p->next;
3365 }
3366 if (p == NULL)
3367 {
3368 p = (PaNameHashIndex*)PaUtil_GroupAllocateMemory(obj->allocGroup, sizeof(PaNameHashIndex));
3369 if (p == NULL)
3370 {
3371 return paInsufficientMemory;
3372 }
3373 p->hash = hash;
3374 p->count = 1;
3375 if (pLast != 0)
3376 {
3377 assert(pLast->next == 0);
3378 pLast->next = p;
3379 }
3380 if (obj->list == 0)
3381 {
3382 obj->list = p;
3383 }
3384 }
3385 else
3386 {
3387 ++p->count;
3388 }
3389 return paNoError;
3390 }
3391
3392 static PaError InitNameHashObject(PaNameHashObject* obj, PaWinWdmFilter* pFilter)
3393 {
3394 int i;
3395
3396 obj->allocGroup = PaUtil_CreateAllocationGroup();
3397 if (obj->allocGroup == NULL)
3398 {
3399 return paInsufficientMemory;
3400 }
3401
3402 for (i = 0; i < pFilter->pinCount; ++i)
3403 {
3404 unsigned m;
3405 PaWinWdmPin* pin = pFilter->pins[i];
3406
3407 if (pin == NULL)
3408 continue;
3409
3410 for (m = 0; m < max(1, pin->inputCount); ++m)
3411 {
3412 const BOOL isInput = (pin->dataFlow == KSPIN_DATAFLOW_OUT);
3413 const wchar_t* name = (pin->inputs == NULL) ? pin->friendlyName : pin->inputs[m]->friendlyName;
3414
3415 PaError result = CreateHashEntry(obj, name, isInput);
3416
3417 if (result != paNoError)
3418 {
3419 return result;
3420 }
3421 }
3422 }
3423 return paNoError;
3424 }
3425
3426 static void DeinitNameHashObject(PaNameHashObject* obj)
3427 {
3428 assert(obj != 0);
3429 PaUtil_FreeAllAllocations(obj->allocGroup);
3430 PaUtil_DestroyAllocationGroup(obj->allocGroup);
3431 memset(obj, 0, sizeof(PaNameHashObject));
3432 }
3433
3434 static unsigned GetNameIndex(PaNameHashObject* obj, const wchar_t* name, const BOOL input)
3435 {
3436 ULONG hash = GetNameHash(name, input);
3437 PaNameHashIndex* p = obj->list;
3438 while (p != NULL)
3439 {
3440 if (p->hash == hash)
3441 {
3442 if (p->count > 1)
3443 {
3444 return (++p->index);
3445 }
3446 else
3447 {
3448 return 0;
3449 }
3450 }
3451
3452 p = p->next;
3453 }
3454 // Should never get here!!
3455 assert(FALSE);
3456 return 0;
3457 }
3458
3459 static PaError ScanDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex hostApiIndex, void **scanResults, int *newDeviceCount )
3460 {
3461 PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
3462 PaError result = paNoError;
3463 PaWinWdmFilter** ppFilters = 0;
3464 PaWinWDMScanDeviceInfosResults *outArgument = 0;
3465 int filterCount = 0;
3466 int totalDeviceCount = 0;
3467 int idxDevice = 0;
3468 DWORD defaultInDevPathSize = 0;
3469 DWORD defaultOutDevPathSize = 0;
3470 wchar_t* defaultInDevPath = 0;
3471 wchar_t* defaultOutDevPath = 0;
3472
3473 ppFilters = BuildFilterList( &filterCount, &totalDeviceCount, &result );
3474 if( result != paNoError )
3475 {
3476 goto error;
3477 }
3478
3479 // Get hold of default device paths for capture & playback
3480 if( waveInMessage(0, DRV_QUERYDEVICEINTERFACESIZE, (DWORD_PTR)&defaultInDevPathSize, 0 ) == MMSYSERR_NOERROR )
3481 {
3482 defaultInDevPath = (wchar_t *)PaUtil_AllocateMemory((defaultInDevPathSize + 1) * sizeof(wchar_t));
3483 waveInMessage(0, DRV_QUERYDEVICEINTERFACE, (DWORD_PTR)defaultInDevPath, defaultInDevPathSize);
3484 }
3485 if( waveOutMessage(0, DRV_QUERYDEVICEINTERFACESIZE, (DWORD_PTR)&defaultOutDevPathSize, 0 ) == MMSYSERR_NOERROR )
3486 {
3487 defaultOutDevPath = (wchar_t *)PaUtil_AllocateMemory((defaultOutDevPathSize + 1) * sizeof(wchar_t));
3488 waveOutMessage(0, DRV_QUERYDEVICEINTERFACE, (DWORD_PTR)defaultOutDevPath, defaultOutDevPathSize);
3489 }
3490
3491 if( totalDeviceCount > 0 )
3492 {
3493 PaWinWdmDeviceInfo *deviceInfoArray = 0;
3494 int idxFilter;
3495 int i;
3496 unsigned devIsDefaultIn = 0, devIsDefaultOut = 0;
3497
3498 /* Allocate the out param for all the info we need */
3499 outArgument = (PaWinWDMScanDeviceInfosResults *) PaUtil_GroupAllocateMemory(
3500 wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults) );
3501 if( !outArgument )
3502 {
3503 result = paInsufficientMemory;
3504 goto error;
3505 }
3506
3507 outArgument->defaultInputDevice = paNoDevice;
3508 outArgument->defaultOutputDevice = paNoDevice;
3509
3510 outArgument->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
3511 wdmHostApi->allocations, sizeof(PaDeviceInfo*) * totalDeviceCount );
3512 if( !outArgument->deviceInfos )
3513 {
3514 result = paInsufficientMemory;
3515 goto error;
3516 }
3517
3518 /* allocate all device info structs in a contiguous block */
3519 deviceInfoArray = (PaWinWdmDeviceInfo*)PaUtil_GroupAllocateMemory(
3520 wdmHostApi->allocations, sizeof(PaWinWdmDeviceInfo) * totalDeviceCount );
3521 if( !deviceInfoArray )
3522 {
3523 result = paInsufficientMemory;
3524 goto error;
3525 }
3526
3527 /* Make sure all items in array */
3528 for( i = 0 ; i < totalDeviceCount; ++i )
3529 {
3530 PaDeviceInfo *deviceInfo = &deviceInfoArray[i].inheritedDeviceInfo;
3531 deviceInfo->structVersion = 2;
3532 deviceInfo->hostApi = hostApiIndex;
3533 deviceInfo->name = 0;
3534 outArgument->deviceInfos[ i ] = deviceInfo;
3535 }
3536
3537 idxDevice = 0;
3538 for (idxFilter = 0; idxFilter < filterCount; ++idxFilter)
3539 {
3540 PaNameHashObject nameHash = {0};
3541 PaWinWdmFilter* pFilter = ppFilters[idxFilter];
3542 if( pFilter == NULL )
3543 continue;
3544
3545 if (InitNameHashObject(&nameHash, pFilter) != paNoError)
3546 {
3547 DeinitNameHashObject(&nameHash);
3548 continue;
3549 }
3550
3551 devIsDefaultIn = (defaultInDevPath && (_wcsicmp(pFilter->devInfo.filterPath, defaultInDevPath) == 0));
3552 devIsDefaultOut = (defaultOutDevPath && (_wcsicmp(pFilter->devInfo.filterPath, defaultOutDevPath) == 0));
3553
3554 for (i = 0; i < pFilter->pinCount; ++i)
3555 {
3556 unsigned m;
3557 ULONG nameIndex = 0;
3558 ULONG nameIndexHash = 0;
3559 PaWinWdmPin* pin = pFilter->pins[i];
3560
3561 if (pin == NULL)
3562 continue;
3563
3564 for (m = 0; m < max(1, pin->inputCount); ++m)
3565 {
3566 PaWinWdmDeviceInfo *wdmDeviceInfo = (PaWinWdmDeviceInfo *)outArgument->deviceInfos[idxDevice];
3567 PaDeviceInfo *deviceInfo = &wdmDeviceInfo->inheritedDeviceInfo;
3568 wchar_t localCompositeName[MAX_PATH];
3569 unsigned nameIndex = 0;
3570 const BOOL isInput = (pin->dataFlow == KSPIN_DATAFLOW_OUT);
3571
3572 wdmDeviceInfo->filter = pFilter;
3573
3574 deviceInfo->structVersion = 2;
3575 deviceInfo->hostApi = hostApiIndex;
3576 deviceInfo->name = wdmDeviceInfo->compositeName;
3577 /* deviceInfo->hostApiSpecificDeviceInfo = &pFilter->devInfo; */
3578
3579 wdmDeviceInfo->pin = pin->pinId;
3580
3581 /* Get the name of the "device" */
3582 if (pin->inputs == NULL)
3583 {
3584 wcsncpy(localCompositeName, pin->friendlyName, MAX_PATH);
3585 wdmDeviceInfo->muxPosition = -1;
3586 wdmDeviceInfo->endpointPinId = pin->endpointPinId;
3587 }
3588 else
3589 {
3590 PaWinWdmMuxedInput* input = pin->inputs[m];
3591 wcsncpy(localCompositeName, input->friendlyName, MAX_PATH);
3592 wdmDeviceInfo->muxPosition = (int)m;
3593 wdmDeviceInfo->endpointPinId = input->endpointPinId;
3594 }
3595
3596 {
3597 /* Get base length */
3598 size_t n = wcslen(localCompositeName);
3599
3600 /* Check if there are more entries with same name (which might very well be the case), if there
3601 are, the name will be postfixed with an index. */
3602 nameIndex = GetNameIndex(&nameHash, localCompositeName, isInput);
3603 if (nameIndex > 0)
3604 {
3605 /* This name has multiple instances, so we post fix with a number */
3606 n += _snwprintf(localCompositeName + n, MAX_PATH - n, L" %u", nameIndex);
3607 }
3608 /* Postfix with filter name */
3609 _snwprintf(localCompositeName + n, MAX_PATH - n, L" (%s)", pFilter->friendlyName);
3610 }
3611
3612 /* Convert wide char string to utf-8 */
3613 WideCharToMultiByte(CP_UTF8, 0, localCompositeName, -1, wdmDeviceInfo->compositeName, MAX_PATH, NULL, NULL);
3614
3615 /* NB! WDM/KS has no concept of a full-duplex device, each pin is either an input or an output */
3616 if (isInput)
3617 {
3618 /* INPUT ! */
3619 deviceInfo->maxInputChannels = pin->maxChannels;
3620 deviceInfo->maxOutputChannels = 0;
3621
3622 /* RoBi NB: Due to the fact that input audio endpoints in Vista (& later OSs) can be the same device, but with
3623 different input mux settings, there might be a discrepancy between the default input device chosen, and
3624 that which will be used by Portaudio. Not much to do about that unfortunately.
3625 */
3626 if ((defaultInDevPath == 0 || devIsDefaultIn) &&
3627 outArgument->defaultInputDevice == paNoDevice)
3628 {
3629 outArgument->defaultInputDevice = idxDevice;
3630 }
3631 }
3632 else
3633 {
3634 /* OUTPUT ! */
3635 deviceInfo->maxInputChannels = 0;
3636 deviceInfo->maxOutputChannels = pin->maxChannels;
3637
3638 if ((defaultOutDevPath == 0 || devIsDefaultOut) &&
3639 outArgument->defaultOutputDevice == paNoDevice)
3640 {
3641 outArgument->defaultOutputDevice = idxDevice;
3642 }
3643 }
3644
3645 /* These low values are not very useful because
3646 * a) The lowest latency we end up with can depend on many factors such
3647 * as the device buffer sizes/granularities, sample rate, channels and format
3648 * b) We cannot know the device buffer sizes until we try to open/use it at
3649 * a particular setting
3650 * So: we give 512x48000Hz frames as the default low input latency
3651 **/
3652 switch (pFilter->devInfo.streamingType)
3653 {
3654 case Type_kWaveCyclic:
3655 if (IsEarlierThanVista())
3656 {
3657 /* XP doesn't tolerate low latency, unless the Process Priority Class is set to REALTIME_PRIORITY_CLASS
3658 through SetPriorityClass, then 10 ms is quite feasible. However, one should then bear in mind that ALL of
3659 the process is running in REALTIME_PRIORITY_CLASS, which might not be appropriate for an application with
3660 a GUI . In this case it is advisable to separate the audio engine in another process and use IPC to communicate
3661 with it. */
3662 deviceInfo->defaultLowInputLatency = 0.02;
3663 deviceInfo->defaultLowOutputLatency = 0.02;
3664 }
3665 else
3666 {
3667 /* This is a conservative estimate. Most WaveCyclic drivers will limit the available latency, but f.i. my Edirol
3668 PCR-A30 can reach 3 ms latency easily... */
3669 deviceInfo->defaultLowInputLatency = 0.01;
3670 deviceInfo->defaultLowOutputLatency = 0.01;
3671 }
3672 deviceInfo->defaultHighInputLatency = (4096.0/48000.0);
3673 deviceInfo->defaultHighOutputLatency = (4096.0/48000.0);
3674 deviceInfo->defaultSampleRate = (double)(pin->defaultSampleRate);
3675 break;
3676 case Type_kWaveRT:
3677 /* This is also a conservative estimate, based on WaveRT polled mode. In polled mode, the latency will be dictated
3678 by the buffer size given by the driver. */
3679 deviceInfo->defaultLowInputLatency = 0.01;
3680 deviceInfo->defaultLowOutputLatency = 0.01;
3681 deviceInfo->defaultHighInputLatency = 0.04;
3682 deviceInfo->defaultHighOutputLatency = 0.04;
3683 deviceInfo->defaultSampleRate = (double)(pin->defaultSampleRate);
3684 break;
3685 default:
3686 assert(0);
3687 break;
3688 }
3689
3690 /* Add reference to filter */
3691 FilterAddRef(wdmDeviceInfo->filter);
3692
3693 assert(idxDevice < totalDeviceCount);
3694 ++idxDevice;
3695 }
3696 }
3697
3698 /* If no one has add ref'd the filter, drop it */
3699 if (pFilter->filterRefCount == 0)
3700 {
3701 FilterFree(pFilter);
3702 }
3703
3704 /* Deinitialize name hash object */
3705 DeinitNameHashObject(&nameHash);
3706 }
3707 }
3708
3709 *scanResults = outArgument;
3710 *newDeviceCount = idxDevice;
3711 return result;
3712
3713 error:
3714 result = DisposeDeviceInfos(hostApi, outArgument, totalDeviceCount);
3715
3716 return result;
3717 }
3718
3719 static PaError CommitDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, PaHostApiIndex index, void *scanResults, int deviceCount )
3720 {
3721 PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
3722
3723 hostApi->info.deviceCount = 0;
3724 hostApi->info.defaultInputDevice = paNoDevice;
3725 hostApi->info.defaultOutputDevice = paNoDevice;
3726
3727 /* Free any old memory which might be in the device info */
3728 if( hostApi->deviceInfos )
3729 {
3730 PaWinWDMScanDeviceInfosResults* localScanResults = (PaWinWDMScanDeviceInfosResults*)PaUtil_GroupAllocateMemory(
3731 wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults));
3732 localScanResults->deviceInfos = hostApi->deviceInfos;
3733
3734 DisposeDeviceInfos(hostApi, &localScanResults, hostApi->info.deviceCount);
3735
3736 hostApi->deviceInfos = NULL;
3737 }
3738
3739 if( scanResults != NULL )
3740 {
3741 PaWinWDMScanDeviceInfosResults *scanDeviceInfosResults = ( PaWinWDMScanDeviceInfosResults * ) scanResults;
3742
3743 if( deviceCount > 0 )
3744 {
3745 /* use the array allocated in ScanDeviceInfos() as our deviceInfos */
3746 hostApi->deviceInfos = scanDeviceInfosResults->deviceInfos;
3747
3748 hostApi->info.defaultInputDevice = scanDeviceInfosResults->defaultInputDevice;
3749 hostApi->info.defaultOutputDevice = scanDeviceInfosResults->defaultOutputDevice;
3750
3751 hostApi->info.deviceCount = deviceCount;
3752 }
3753
3754 PaUtil_GroupFreeMemory( wdmHostApi->allocations, scanDeviceInfosResults );
3755 }
3756
3757 return paNoError;
3758
3759 }
3760
3761 static PaError DisposeDeviceInfos( struct PaUtilHostApiRepresentation *hostApi, void *scanResults, int deviceCount )
3762 {
3763 PaWinWdmHostApiRepresentation *winDsHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
3764
3765 if( scanResults != NULL )
3766 {
3767 PaWinWDMScanDeviceInfosResults *scanDeviceInfosResults = ( PaWinWDMScanDeviceInfosResults * ) scanResults;
3768
3769 if( scanDeviceInfosResults->deviceInfos )
3770 {
3771 int i;
3772 for (i = 0; i < deviceCount; ++i)
3773 {
3774 PaWinWdmDeviceInfo* pDevice = (PaWinWdmDeviceInfo*)scanDeviceInfosResults->deviceInfos[i];
3775 if (pDevice->filter != 0)
3776 {
3777 FilterFree(pDevice->filter);
3778 }
3779 }
3780
3781 PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults->deviceInfos[0] ); /* all device info structs are allocated in a block so we can destroy them here */
3782 PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults->deviceInfos );
3783 }
3784
3785 PaUtil_GroupFreeMemory( winDsHostApi->allocations, scanDeviceInfosResults );
3786 }
3787
3788 return paNoError;
3789
3790 }
3791
3792 PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
3793 {
3794 PaError result = paNoError;
3795 int deviceCount = 0;
3796 void *scanResults = 0;
3797 PaWinWdmHostApiRepresentation *wdmHostApi = NULL;
3798
3799 PA_LOGE_;
3800
3801 #ifdef PA_WDMKS_SET_TREF
3802 tRef = PaUtil_GetTime();
3803 #endif
3804
3805 /*
3806 Attempt to load the KSUSER.DLL without which we cannot create pins
3807 We will unload this on termination
3808 */
3809 if(DllKsUser == NULL)
3810 {
3811 DllKsUser = LoadLibrary(TEXT("ksuser.dll"));
3812 if(DllKsUser == NULL)
3813 goto error;
3814 }
3815 FunctionKsCreatePin = (KSCREATEPIN*)GetProcAddress(DllKsUser, "KsCreatePin");
3816 if(FunctionKsCreatePin == NULL)
3817 goto error;
3818
3819 /* Attempt to load AVRT.DLL, if we can't, then we'll just use time critical prio instead... */
3820 if(paWinWDMKSAvRtEntryPoints.hInstance == NULL)
3821 {
3822 paWinWDMKSAvRtEntryPoints.hInstance = LoadLibrary(TEXT("avrt.dll"));
3823 if (paWinWDMKSAvRtEntryPoints.hInstance != NULL)
3824 {
3825 paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics =
3826 (HANDLE(WINAPI*)(LPCSTR,LPDWORD))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance,"AvSetMmThreadCharacteristicsA");
3827 paWinWDMKSAvRtEntryPoints.AvRevertMmThreadCharacteristics =
3828 (BOOL(WINAPI*)(HANDLE))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance, "AvRevertMmThreadCharacteristics");
3829 paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority =
3830 (BOOL(WINAPI*)(HANDLE,PA_AVRT_PRIORITY))GetProcAddress(paWinWDMKSAvRtEntryPoints.hInstance, "AvSetMmThreadPriority");
3831 }
3832 }
3833
3834 wdmHostApi = (PaWinWdmHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinWdmHostApiRepresentation) );
3835 if( !wdmHostApi )
3836 {
3837 result = paInsufficientMemory;
3838 goto error;
3839 }
3840
3841 wdmHostApi->allocations = PaUtil_CreateAllocationGroup();
3842 if( !wdmHostApi->allocations )
3843 {
3844 result = paInsufficientMemory;
3845 goto error;
3846 }
3847
3848 *hostApi = &wdmHostApi->inheritedHostApiRep;
3849 (*hostApi)->info.structVersion = 1;
3850 (*hostApi)->info.type = paWDMKS;
3851 (*hostApi)->info.name = "Windows WDM-KS";
3852
3853 /* these are all updated by CommitDeviceInfos() */
3854 (*hostApi)->info.deviceCount = 0;
3855 (*hostApi)->info.defaultInputDevice = paNoDevice;
3856 (*hostApi)->info.defaultOutputDevice = paNoDevice;
3857 (*hostApi)->deviceInfos = 0;
3858
3859 result = ScanDeviceInfos(&wdmHostApi->inheritedHostApiRep, hostApiIndex, &scanResults, &deviceCount);
3860 if (result != paNoError)
3861 {
3862 goto error;
3863 }
3864
3865 CommitDeviceInfos(&wdmHostApi->inheritedHostApiRep, hostApiIndex, scanResults, deviceCount);
3866
3867 (*hostApi)->Terminate = Terminate;
3868 (*hostApi)->OpenStream = OpenStream;
3869 (*hostApi)->IsFormatSupported = IsFormatSupported;
3870 /* In preparation for hotplug
3871 (*hostApi)->ScanDeviceInfos = ScanDeviceInfos;
3872 (*hostApi)->CommitDeviceInfos = CommitDeviceInfos;
3873 (*hostApi)->DisposeDeviceInfos = DisposeDeviceInfos;
3874 */
3875 PaUtil_InitializeStreamInterface( &wdmHostApi->callbackStreamInterface, CloseStream, StartStream,
3876 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
3877 GetStreamTime, GetStreamCpuLoad,
3878 PaUtil_DummyRead, PaUtil_DummyWrite,
3879 PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
3880
3881 PaUtil_InitializeStreamInterface( &wdmHostApi->blockingStreamInterface, CloseStream, StartStream,
3882 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
3883 GetStreamTime, PaUtil_DummyGetCpuLoad,
3884 ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
3885
3886 PA_LOGL_;
3887 return result;
3888
3889 error:
3890 Terminate( (PaUtilHostApiRepresentation*)wdmHostApi );
3891
3892 PA_LOGL_;
3893 return result;
3894 }
3895
3896
3897 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
3898 {
3899 PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
3900 PA_LOGE_;
3901
3902 /* Do not unload the libraries */
3903 if( DllKsUser != NULL )
3904 {
3905 FreeLibrary( DllKsUser );
3906 DllKsUser = NULL;
3907 }
3908
3909 if( paWinWDMKSAvRtEntryPoints.hInstance != NULL )
3910 {
3911 FreeLibrary( paWinWDMKSAvRtEntryPoints.hInstance );
3912 paWinWDMKSAvRtEntryPoints.hInstance = NULL;
3913 }
3914
3915 if( wdmHostApi)
3916 {
3917 PaWinWDMScanDeviceInfosResults* localScanResults = (PaWinWDMScanDeviceInfosResults*)PaUtil_GroupAllocateMemory(
3918 wdmHostApi->allocations, sizeof(PaWinWDMScanDeviceInfosResults));
3919 localScanResults->deviceInfos = hostApi->deviceInfos;
3920 DisposeDeviceInfos(hostApi, localScanResults, hostApi->info.deviceCount);
3921
3922 if( wdmHostApi->allocations )
3923 {
3924 PaUtil_FreeAllAllocations( wdmHostApi->allocations );
3925 PaUtil_DestroyAllocationGroup( wdmHostApi->allocations );
3926 }
3927 PaUtil_FreeMemory( wdmHostApi );
3928 }
3929 PA_LOGL_;
3930 }
3931
3932 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
3933 const PaStreamParameters *inputParameters,
3934 const PaStreamParameters *outputParameters,
3935 double sampleRate )
3936 {
3937 int inputChannelCount, outputChannelCount;
3938 PaSampleFormat inputSampleFormat, outputSampleFormat;
3939 PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
3940 PaWinWdmFilter* pFilter;
3941 int result = paFormatIsSupported;
3942 WAVEFORMATEXTENSIBLE wfx;
3943 PaWinWaveFormatChannelMask channelMask;
3944
3945 PA_LOGE_;
3946
3947 if( inputParameters )
3948 {
3949 PaWinWdmDeviceInfo* pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
3950 PaWinWdmPin* pin;
3951 unsigned fmt;
3952 unsigned long testFormat = 0;
3953 unsigned validBits = 0;
3954
3955 inputChannelCount = inputParameters->channelCount;
3956 inputSampleFormat = inputParameters->sampleFormat;
3957
3958 /* all standard sample formats are supported by the buffer adapter,
3959 this implementation doesn't support any custom sample formats */
3960 if( inputSampleFormat & paCustomFormat )
3961 {
3962 PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "IsFormatSupported: Custom input format not supported");
3963 return paSampleFormatNotSupported;
3964 }
3965
3966 /* unless alternate device specification is supported, reject the use of
3967 paUseHostApiSpecificDeviceSpecification */
3968
3969 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
3970 {
3971 PaWinWDM_SetLastErrorInfo(paInvalidDevice, "IsFormatSupported: paUseHostApiSpecificDeviceSpecification not supported");
3972 return paInvalidDevice;
3973 }
3974
3975 /* check that input device can support inputChannelCount */
3976 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
3977 {
3978 PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "IsFormatSupported: Invalid input channel count");
3979 return paInvalidChannelCount;
3980 }
3981
3982 /* validate inputStreamInfo */
3983 if( inputParameters->hostApiSpecificStreamInfo )
3984 {
3985 PaWinWDM_SetLastErrorInfo(paIncompatibleHostApiSpecificStreamInfo, "Host API stream info not supported");
3986 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
3987 }
3988
3989 pFilter = pDeviceInfo->filter;
3990 pin = pFilter->pins[pDeviceInfo->pin];
3991
3992 /* Find out the testing format */
3993 for (fmt = paFloat32; fmt <= paUInt8; fmt <<= 1)
3994 {
3995 if ((fmt & pin->formats) != 0)
3996 {
3997 /* Found a matching format! */
3998 testFormat = fmt;
3999 break;
4000 }
4001 }
4002 if (testFormat == 0)
4003 {
4004 PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(capture) failed: no testformat found!");
4005 return paUnanticipatedHostError;
4006 }
4007
4008 /* Due to special considerations, WaveRT devices with paInt24 should be tested with paInt32 and
4009 valid bits = 24 (instead of 24 bit samples) */
4010 if (pFilter->devInfo.streamingType == Type_kWaveRT && testFormat == paInt24)
4011 {
4012 PA_DEBUG(("IsFormatSupported (capture): WaveRT overriding testFormat paInt24 with paInt32 (24 valid bits)"));
4013 testFormat = paInt32;
4014 validBits = 24;
4015 }
4016
4017 /* Check that the input format is supported */
4018 channelMask = PaWin_DefaultChannelMask(inputChannelCount);
4019 PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
4020 inputChannelCount,
4021 testFormat,
4022 PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
4023 sampleRate,
4024 channelMask );
4025 if (validBits != 0)
4026 {
4027 wfx.Samples.wValidBitsPerSample = validBits;
4028 }
4029
4030 result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
4031 if( result != paNoError )
4032 {
4033 /* Try a WAVE_FORMAT_PCM instead */
4034 PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
4035 inputChannelCount,
4036 testFormat,
4037 PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
4038 sampleRate);
4039
4040 if (validBits != 0)
4041 {
4042 wfx.Samples.wValidBitsPerSample = validBits;
4043 }
4044
4045 result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
4046 if( result != paNoError )
4047 {
4048 PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(capture) failed: sr=%u,ch=%u,bits=%u", wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample);
4049 return result;
4050 }
4051 }
4052 }
4053 else
4054 {
4055 inputChannelCount = 0;
4056 }
4057
4058 if( outputParameters )
4059 {
4060 PaWinWdmDeviceInfo* pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];
4061 PaWinWdmPin* pin;
4062 unsigned fmt;
4063 unsigned long testFormat = 0;
4064 unsigned validBits = 0;
4065
4066 outputChannelCount = outputParameters->channelCount;
4067 outputSampleFormat = outputParameters->sampleFormat;
4068
4069 /* all standard sample formats are supported by the buffer adapter,
4070 this implementation doesn't support any custom sample formats */
4071 if( outputSampleFormat & paCustomFormat )
4072 {
4073 PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "IsFormatSupported: Custom output format not supported");
4074 return paSampleFormatNotSupported;
4075 }
4076
4077 /* unless alternate device specification is supported, reject the use of
4078 paUseHostApiSpecificDeviceSpecification */
4079
4080 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
4081 {
4082 PaWinWDM_SetLastErrorInfo(paInvalidDevice, "IsFormatSupported: paUseHostApiSpecificDeviceSpecification not supported");
4083 return paInvalidDevice;
4084 }
4085
4086 /* check that output device can support outputChannelCount */
4087 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
4088 {
4089 PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid output channel count");
4090 return paInvalidChannelCount;
4091 }
4092
4093 /* validate outputStreamInfo */
4094 if( outputParameters->hostApiSpecificStreamInfo )
4095 {
4096 PaWinWDM_SetLastErrorInfo(paIncompatibleHostApiSpecificStreamInfo, "Host API stream info not supported");
4097 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
4098 }
4099
4100 pFilter = pDeviceInfo->filter;
4101 pin = pFilter->pins[pDeviceInfo->pin];
4102
4103 /* Find out the testing format */
4104 for (fmt = paFloat32; fmt <= paUInt8; fmt <<= 1)
4105 {
4106 if ((fmt & pin->formats) != 0)
4107 {
4108 /* Found a matching format! */
4109 testFormat = fmt;
4110 break;
4111 }
4112 }
4113 if (testFormat == 0)
4114 {
4115 PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(render) failed: no testformat found!");
4116 return paUnanticipatedHostError;
4117 }
4118
4119 /* Due to special considerations, WaveRT devices with paInt24 should be tested with paInt32 and
4120 valid bits = 24 (instead of 24 bit samples) */
4121 if (pFilter->devInfo.streamingType == Type_kWaveRT && testFormat == paInt24)
4122 {
4123 PA_DEBUG(("IsFormatSupported (render): WaveRT overriding testFormat paInt24 with paInt32 (24 valid bits)"));
4124 testFormat = paInt32;
4125 validBits = 24;
4126 }
4127
4128 /* Check that the output format is supported */
4129 channelMask = PaWin_DefaultChannelMask(outputChannelCount);
4130 PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
4131 outputChannelCount,
4132 testFormat,
4133 PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
4134 sampleRate,
4135 channelMask );
4136
4137 if (validBits != 0)
4138 {
4139 wfx.Samples.wValidBitsPerSample = validBits;
4140 }
4141
4142 result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
4143 if( result != paNoError )
4144 {
4145 /* Try a WAVE_FORMAT_PCM instead */
4146 PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
4147 outputChannelCount,
4148 testFormat,
4149 PaWin_SampleFormatToLinearWaveFormatTag(testFormat),
4150 sampleRate);
4151
4152 if (validBits != 0)
4153 {
4154 wfx.Samples.wValidBitsPerSample = validBits;
4155 }
4156
4157 result = PinIsFormatSupported(pin, (const WAVEFORMATEX*)&wfx);
4158 if( result != paNoError )
4159 {
4160 PaWinWDM_SetLastErrorInfo(result, "IsFormatSupported(render) failed: %u,%u,%u", wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample);
4161 return result;
4162 }
4163 }
4164
4165 }
4166 else
4167 {
4168 outputChannelCount = 0;
4169 }
4170
4171 /*
4172 IMPLEMENT ME:
4173
4174 - if a full duplex stream is requested, check that the combination
4175 of input and output parameters is supported if necessary
4176
4177 - check that the device supports sampleRate
4178
4179 Because the buffer adapter handles conversion between all standard
4180 sample formats, the following checks are only required if paCustomFormat
4181 is implemented, or under some other unusual conditions.
4182
4183 - check that input device can support inputSampleFormat, or that
4184 we have the capability to convert from inputSampleFormat to
4185 a native format
4186
4187 - check that output device can support outputSampleFormat, or that
4188 we have the capability to convert from outputSampleFormat to
4189 a native format
4190 */
4191 if((inputChannelCount == 0)&&(outputChannelCount == 0))
4192 {
4193 PaWinWDM_SetLastErrorInfo(paSampleFormatNotSupported, "No input or output channels defined");
4194 result = paSampleFormatNotSupported; /* Not right error */
4195 }
4196
4197 PA_LOGL_;
4198 return result;
4199 }
4200
4201 static void ResetStreamEvents(PaWinWdmStream* stream)
4202 {
4203 unsigned i;
4204 ResetEvent(stream->eventAbort);
4205 ResetEvent(stream->eventStreamStart[StreamStart_kOk]);
4206 ResetEvent(stream->eventStreamStart[StreamStart_kFailed]);
4207
4208 for (i=0; i<stream->capture.noOfPackets; ++i)
4209 {
4210 if (stream->capture.events && stream->capture.events[i])
4211 {
4212 ResetEvent(stream->capture.events[i]);
4213 }
4214 }
4215
4216 for (i=0; i<stream->render.noOfPackets; ++i)
4217 {
4218 if (stream->render.events && stream->render.events[i])
4219 {
4220 ResetEvent(stream->render.events[i]);
4221 }
4222 }
4223 }
4224
4225 static void CloseStreamEvents(PaWinWdmStream* stream)
4226 {
4227 unsigned i;
4228 PaWinWdmIOInfo* ios[2] = { &stream->capture, &stream->render };
4229
4230 if (stream->eventAbort)
4231 {
4232 CloseHandle(stream->eventAbort);
4233 stream->eventAbort = 0;
4234 }
4235 if (stream->eventStreamStart[StreamStart_kOk])
4236 {
4237 CloseHandle(stream->eventStreamStart[StreamStart_kOk]);
4238 }
4239 if (stream->eventStreamStart[StreamStart_kFailed])
4240 {
4241 CloseHandle(stream->eventStreamStart[StreamStart_kFailed]);
4242 }
4243
4244 for (i = 0; i < 2; ++i)
4245 {
4246 unsigned j;
4247 /* Unregister notification handles for WaveRT */
4248 if (ios[i]->pPin && ios[i]->pPin->parentFilter->devInfo.streamingType == Type_kWaveRT &&
4249 ios[i]->pPin->pinKsSubType == SubType_kNotification &&
4250 ios[i]->events != 0)
4251 {
4252 PinUnregisterNotificationHandle(ios[i]->pPin, ios[i]->events[0]);
4253 }
4254
4255 for (j=0; j < ios[i]->noOfPackets; ++j)
4256 {
4257 if (ios[i]->events && ios[i]->events[j])
4258 {
4259 CloseHandle(ios[i]->events[j]);
4260 ios[i]->events[j] = 0;
4261 }
4262 }
4263 }
4264 }
4265
4266 static unsigned NextPowerOf2(unsigned val)
4267 {
4268 val--;
4269 val = (val >> 1) | val;
4270 val = (val >> 2) | val;
4271 val = (val >> 4) | val;
4272 val = (val >> 8) | val;
4273 val = (val >> 16) | val;
4274 return ++val;
4275 }
4276
4277 static PaError ValidateSpecificStreamParameters(
4278 const PaStreamParameters *streamParameters,
4279 const PaWinWDMKSInfo *streamInfo,
4280 unsigned isInput)
4281 {
4282 if( streamInfo )
4283 {
4284 if( streamInfo->size != sizeof( PaWinWDMKSInfo )
4285 || streamInfo->version != 1 )
4286 {
4287 PA_DEBUG(("Stream parameters: size or version not correct"));
4288 return paIncompatibleHostApiSpecificStreamInfo;
4289 }
4290
4291 if (!!(streamInfo->flags & ~(paWinWDMKSOverrideFramesize | paWinWDMKSUseGivenChannelMask)))
4292 {
4293 PA_DEBUG(("Stream parameters: non supported flags set"));
4294 return paIncompatibleHostApiSpecificStreamInfo;
4295 }
4296
4297 if (streamInfo->noOfPackets != 0 &&
4298 (streamInfo->noOfPackets < 2 || streamInfo->noOfPackets > 8))
4299 {
4300 PA_DEBUG(("Stream parameters: noOfPackets %u out of range [2,8]", streamInfo->noOfPackets));
4301 return paIncompatibleHostApiSpecificStreamInfo;
4302 }
4303
4304 if (streamInfo->flags & paWinWDMKSUseGivenChannelMask)
4305 {
4306 if (isInput)
4307 {
4308 PA_DEBUG(("Stream parameters: Channels mask setting not supported for input stream"));
4309 return paIncompatibleHostApiSpecificStreamInfo;
4310 }
4311
4312 if (streamInfo->channelMask & PAWIN_SPEAKER_RESERVED)
4313 {
4314 PA_DEBUG(("Stream parameters: Given channels mask 0x%08X not supported", streamInfo->channelMask));
4315 return paIncompatibleHostApiSpecificStreamInfo;
4316 }
4317 }
4318
4319 }
4320
4321 return paNoError;
4322 }
4323
4324
4325
4326
4327 /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
4328
4329 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
4330 PaStream** s,
4331 const PaStreamParameters *inputParameters,
4332 const PaStreamParameters *outputParameters,
4333 double sampleRate,
4334 unsigned long framesPerUserBuffer,
4335 PaStreamFlags streamFlags,
4336 PaStreamCallback *streamCallback,
4337 void *userData )
4338 {
4339 PaError result = paNoError;
4340 PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
4341 PaWinWdmStream *stream = 0;
4342 /* unsigned long framesPerHostBuffer; these may not be equivalent for all implementations */
4343 PaSampleFormat inputSampleFormat, outputSampleFormat;
4344 PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
4345 int userInputChannels,userOutputChannels;
4346 WAVEFORMATEXTENSIBLE wfx;
4347
4348 PA_LOGE_;
4349 PA_DEBUG(("OpenStream:sampleRate = %f\n",sampleRate));
4350 PA_DEBUG(("OpenStream:framesPerBuffer = %lu\n",framesPerUserBuffer));
4351
4352 if( inputParameters )
4353 {
4354 userInputChannels = inputParameters->channelCount;
4355 inputSampleFormat = inputParameters->sampleFormat;
4356
4357 /* unless alternate device specification is supported, reject the use of
4358 paUseHostApiSpecificDeviceSpecification */
4359
4360 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
4361 {
4362 PaWinWDM_SetLastErrorInfo(paInvalidDevice, "paUseHostApiSpecificDeviceSpecification(in) not supported");
4363 return paInvalidDevice;
4364 }
4365
4366 /* check that input device can support stream->userInputChannels */
4367 if( userInputChannels > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
4368 {
4369 PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid input channel count");
4370 return paInvalidChannelCount;
4371 }
4372
4373 /* validate inputStreamInfo */
4374 result = ValidateSpecificStreamParameters(inputParameters, inputParameters->hostApiSpecificStreamInfo, 1 );
4375 if(result != paNoError)
4376 {
4377 PaWinWDM_SetLastErrorInfo(result, "Host API stream info not supported (in)");
4378 return result; /* this implementation doesn't use custom stream info */
4379 }
4380 }
4381 else
4382 {
4383 userInputChannels = 0;
4384 inputSampleFormat = paInt16; /* Suppress 'uninitialised var' warnings. */
4385 }
4386
4387 if( outputParameters )
4388 {
4389 userOutputChannels = outputParameters->channelCount;
4390 outputSampleFormat = outputParameters->sampleFormat;
4391
4392 /* unless alternate device specification is supported, reject the use of
4393 paUseHostApiSpecificDeviceSpecification */
4394
4395 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
4396 {
4397 PaWinWDM_SetLastErrorInfo(paInvalidDevice, "paUseHostApiSpecificDeviceSpecification(out) not supported");
4398 return paInvalidDevice;
4399 }
4400
4401 /* check that output device can support stream->userInputChannels */
4402 if( userOutputChannels > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
4403 {
4404 PaWinWDM_SetLastErrorInfo(paInvalidChannelCount, "Invalid output channel count");
4405 return paInvalidChannelCount;
4406 }
4407
4408 /* validate outputStreamInfo */
4409 result = ValidateSpecificStreamParameters( outputParameters, outputParameters->hostApiSpecificStreamInfo, 0 );
4410 if (result != paNoError)
4411 {
4412 PaWinWDM_SetLastErrorInfo(result, "Host API stream info not supported (out)");
4413 return result; /* this implementation doesn't use custom stream info */
4414 }
4415 }
4416 else
4417 {
4418 userOutputChannels = 0;
4419 outputSampleFormat = paInt16; /* Suppress 'uninitialized var' warnings. */
4420 }
4421
4422 /* validate platform specific flags */
4423 if( (streamFlags & paPlatformSpecificFlags) != 0 )
4424 {
4425 PaWinWDM_SetLastErrorInfo(paInvalidFlag, "Invalid flag supplied");
4426 return paInvalidFlag; /* unexpected platform specific flag */
4427 }
4428
4429 stream = (PaWinWdmStream*)PaUtil_AllocateMemory( sizeof(PaWinWdmStream) );
4430 if( !stream )
4431 {
4432 result = paInsufficientMemory;
4433 goto error;
4434 }
4435
4436 /* Create allocation group */
4437 stream->allocGroup = PaUtil_CreateAllocationGroup();
4438 if( !stream->allocGroup )
4439 {
4440 result = paInsufficientMemory;
4441 goto error;
4442 }
4443
4444 /* Zero the stream object */
4445 /* memset((void*)stream,0,sizeof(PaWinWdmStream)); */
4446
4447 if( streamCallback )
4448 {
4449 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
4450 &wdmHostApi->callbackStreamInterface, streamCallback, userData );
4451 }
4452 else
4453 {
4454 /* PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
4455 &wdmHostApi->blockingStreamInterface, streamCallback, userData ); */
4456
4457 /* We don't support the blocking API yet */
4458 PA_DEBUG(("Blocking API not supported yet!\n"));
4459 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Blocking API not supported yet");
4460 result = paUnanticipatedHostError;
4461 goto error;
4462 }
4463
4464 PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
4465
4466 /* Instantiate the input pin if necessary */
4467 if(userInputChannels > 0)
4468 {
4469 PaWinWdmFilter* pFilter;
4470 PaWinWdmDeviceInfo* pDeviceInfo;
4471 PaWinWdmPin* pPin;
4472 unsigned validBitsPerSample = 0;
4473 PaWinWaveFormatChannelMask channelMask = PaWin_DefaultChannelMask( userInputChannels );
4474
4475 result = paSampleFormatNotSupported;
4476 pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
4477 pFilter = pDeviceInfo->filter;
4478 pPin = pFilter->pins[pDeviceInfo->pin];
4479
4480 stream->userInputChannels = userInputChannels;
4481
4482 hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat( pPin->formats, inputSampleFormat );
4483 if (hostInputSampleFormat == paSampleFormatNotSupported)
4484 {
4485 result = paUnanticipatedHostError;
4486 PaWinWDM_SetLastErrorInfo(result, "PU_SCAF(%X,%X) failed (input)", pPin->formats, inputSampleFormat);
4487 goto error;
4488 }
4489 else if (pFilter->devInfo.streamingType == Type_kWaveRT && hostInputSampleFormat == paInt24)
4490 {
4491 /* For WaveRT, we choose 32 bit format instead of paInt24, since we MIGHT need to align buffer on a
4492 128 byte boundary (see PinGetBuffer) */
4493 hostInputSampleFormat = paInt32;
4494 /* But we'll tell the driver that it's 24 bit in 32 bit container */
4495 validBitsPerSample = 24;
4496 }
4497
4498 while (hostInputSampleFormat <= paUInt8)
4499 {
4500 unsigned channelsToProbe = stream->userInputChannels;
4501 /* Some or all KS devices can only handle the exact number of channels
4502 * they specify. But PortAudio clients expect to be able to
4503 * at least specify mono I/O on a multi-channel device
4504 * If this is the case, then we will do the channel mapping internally
4505 * The following loop tests this case
4506 **/
4507 while (1)
4508 {
4509 PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
4510 channelsToProbe,
4511 hostInputSampleFormat,
4512 PaWin_SampleFormatToLinearWaveFormatTag(hostInputSampleFormat),
4513 sampleRate,
4514 channelMask );
4515 stream->capture.bytesPerFrame = wfx.Format.nBlockAlign;
4516 if (validBitsPerSample != 0)
4517 {
4518 wfx.Samples.wValidBitsPerSample = validBitsPerSample;
4519 }
4520 stream->capture.pPin = FilterCreatePin(pFilter, pPin->pinId, (WAVEFORMATEX*)&wfx, &result);
4521 stream->deviceInputChannels = channelsToProbe;
4522
4523 if( result != paNoError && result != paDeviceUnavailable )
4524 {
4525 /* Try a WAVE_FORMAT_PCM instead */
4526 PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
4527 channelsToProbe,
4528 hostInputSampleFormat,
4529 PaWin_SampleFormatToLinearWaveFormatTag(hostInputSampleFormat),
4530 sampleRate);
4531 if (validBitsPerSample != 0)
4532 {
4533 wfx.Samples.wValidBitsPerSample = validBitsPerSample;
4534 }
4535 stream->capture.pPin = FilterCreatePin(pFilter, pPin->pinId, (const WAVEFORMATEX*)&wfx, &result);
4536 }
4537
4538 if (result == paDeviceUnavailable) goto occupied;
4539
4540 if (result == paNoError)
4541 {
4542 /* We're done */
4543 break;
4544 }
4545
4546 if (channelsToProbe < (unsigned)pPin->maxChannels)
4547 {
4548 /* Go to next multiple of 2 */
4549 channelsToProbe = min((((channelsToProbe>>1)+1)<<1), (unsigned)pPin->maxChannels);
4550 continue;
4551 }
4552
4553 break;
4554 }
4555
4556 if (result == paNoError)
4557 {
4558 /* We're done */
4559 break;
4560 }
4561
4562 /* Go to next format in line with lower resolution */
4563 hostInputSampleFormat <<= 1;
4564 }
4565
4566 if(stream->capture.pPin == NULL)
4567 {
4568 PaWinWDM_SetLastErrorInfo(result, "Failed to create capture pin: sr=%u,ch=%u,bits=%u,align=%u",
4569 wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample, wfx.Format.nBlockAlign);
4570 goto error;
4571 }
4572
4573 /* Select correct mux input on MUX node of topology filter */
4574 if (pDeviceInfo->muxPosition >= 0)
4575 {
4576 assert(pPin->parentFilter->topologyFilter != NULL);
4577
4578 result = FilterUse(pPin->parentFilter->topologyFilter);
4579 if (result != paNoError)
4580 {
4581 PaWinWDM_SetLastErrorInfo(result, "Failed to open topology filter");
4582 goto error;
4583 }
4584
4585 result = WdmSetMuxNodeProperty(pPin->parentFilter->topologyFilter->handle,
4586 pPin->inputs[pDeviceInfo->muxPosition]->muxNodeId,
4587 pPin->inputs[pDeviceInfo->muxPosition]->muxPinId);
4588
4589 FilterRelease(pPin->parentFilter->topologyFilter);
4590
4591 if(result != paNoError)
4592 {
4593 PaWinWDM_SetLastErrorInfo(result, "Failed to set topology mux node");
4594 goto error;
4595 }
4596 }
4597
4598 stream->capture.bytesPerSample = stream->capture.bytesPerFrame / stream->deviceInputChannels;
4599 stream->capture.pPin->frameSize /= stream->capture.bytesPerFrame;
4600 PA_DEBUG(("Capture pin frames: %d\n",stream->capture.pPin->frameSize));
4601 }
4602 else
4603 {
4604 hostInputSampleFormat = (PaSampleFormat)0; /* Avoid uninitialized variable warning */
4605
4606 stream->capture.pPin = NULL;
4607 stream->capture.bytesPerFrame = 0;
4608 }
4609
4610 /* Instantiate the output pin if necessary */
4611 if(userOutputChannels > 0)
4612 {
4613 PaWinWdmFilter* pFilter;
4614 PaWinWdmDeviceInfo* pDeviceInfo;
4615 PaWinWdmPin* pPin;
4616 PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)(outputParameters->hostApiSpecificStreamInfo);
4617 unsigned validBitsPerSample = 0;
4618 PaWinWaveFormatChannelMask channelMask = PaWin_DefaultChannelMask( userOutputChannels );
4619 if (pInfo && (pInfo->flags & paWinWDMKSUseGivenChannelMask))
4620 {
4621 PA_DEBUG(("Using channelMask 0x%08X instead of default 0x%08X\n",
4622 pInfo->channelMask,
4623 channelMask));
4624 channelMask = pInfo->channelMask;
4625 }
4626
4627 result = paSampleFormatNotSupported;
4628 pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];
4629 pFilter = pDeviceInfo->filter;
4630 pPin = pFilter->pins[pDeviceInfo->pin];
4631
4632 stream->userOutputChannels = userOutputChannels;
4633
4634 hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( pPin->formats, outputSampleFormat );
4635 if (hostOutputSampleFormat == paSampleFormatNotSupported)
4636 {
4637 result = paUnanticipatedHostError;
4638 PaWinWDM_SetLastErrorInfo(result, "PU_SCAF(%X,%X) failed (output)", pPin->formats, hostOutputSampleFormat);
4639 goto error;
4640 }
4641 else if (pFilter->devInfo.streamingType == Type_kWaveRT && hostOutputSampleFormat == paInt24)
4642 {
4643 /* For WaveRT, we choose 32 bit format instead of paInt24, since we MIGHT need to align buffer on a
4644 128 byte boundary (see PinGetBuffer) */
4645 hostOutputSampleFormat = paInt32;
4646 /* But we'll tell the driver that it's 24 bit in 32 bit container */
4647 validBitsPerSample = 24;
4648 }
4649
4650 while (hostOutputSampleFormat <= paUInt8)
4651 {
4652 unsigned channelsToProbe = stream->userOutputChannels;
4653 /* Some or all KS devices can only handle the exact number of channels
4654 * they specify. But PortAudio clients expect to be able to
4655 * at least specify mono I/O on a multi-channel device
4656 * If this is the case, then we will do the channel mapping internally
4657 * The following loop tests this case
4658 **/
4659 while (1)
4660 {
4661 PaWin_InitializeWaveFormatExtensible((PaWinWaveFormat*)&wfx,
4662 channelsToProbe,
4663 hostOutputSampleFormat,
4664 PaWin_SampleFormatToLinearWaveFormatTag(hostOutputSampleFormat),
4665 sampleRate,
4666 channelMask );
4667 stream->render.bytesPerFrame = wfx.Format.nBlockAlign;
4668 if (validBitsPerSample != 0)
4669 {
4670 wfx.Samples.wValidBitsPerSample = validBitsPerSample;
4671 }
4672 stream->render.pPin = FilterCreatePin(pFilter, pPin->pinId, (WAVEFORMATEX*)&wfx, &result);
4673 stream->deviceOutputChannels = channelsToProbe;
4674
4675 if( result != paNoError && result != paDeviceUnavailable )
4676 {
4677 PaWin_InitializeWaveFormatEx((PaWinWaveFormat*)&wfx,
4678 channelsToProbe,
4679 hostOutputSampleFormat,
4680 PaWin_SampleFormatToLinearWaveFormatTag(hostOutputSampleFormat),
4681 sampleRate);
4682 if (validBitsPerSample != 0)
4683 {
4684 wfx.Samples.wValidBitsPerSample = validBitsPerSample;
4685 }
4686 stream->render.pPin = FilterCreatePin(pFilter, pPin->pinId, (const WAVEFORMATEX*)&wfx, &result);
4687 }
4688
4689 if (result == paDeviceUnavailable) goto occupied;
4690
4691 if (result == paNoError)
4692 {
4693 /* We're done */
4694 break;
4695 }
4696
4697 if (channelsToProbe < (unsigned)pPin->maxChannels)
4698 {
4699 /* Go to next multiple of 2 */
4700 channelsToProbe = min((((channelsToProbe>>1)+1)<<1), (unsigned)pPin->maxChannels);
4701 continue;
4702 }
4703
4704 break;
4705 };
4706
4707 if (result == paNoError)
4708 {
4709 /* We're done */
4710 break;
4711 }
4712
4713 /* Go to next format in line with lower resolution */
4714 hostOutputSampleFormat <<= 1;
4715 }
4716
4717 if(stream->render.pPin == NULL)
4718 {
4719 PaWinWDM_SetLastErrorInfo(result, "Failed to create render pin: sr=%u,ch=%u,bits=%u,align=%u",
4720 wfx.Format.nSamplesPerSec, wfx.Format.nChannels, wfx.Format.wBitsPerSample, wfx.Format.nBlockAlign);
4721 goto error;
4722 }
4723
4724 stream->render.bytesPerSample = stream->render.bytesPerFrame / stream->deviceOutputChannels;
4725 stream->render.pPin->frameSize /= stream->render.bytesPerFrame;
4726 PA_DEBUG(("Render pin frames: %d\n",stream->render.pPin->frameSize));
4727 }
4728 else
4729 {
4730 hostOutputSampleFormat = (PaSampleFormat)0; /* Avoid uninitialized variable warning */
4731
4732 stream->render.pPin = NULL;
4733 stream->render.bytesPerFrame = 0;
4734 }
4735
4736 /* Calculate the framesPerHostXxxxBuffer size based upon the suggested latency values */
4737 /* Record the buffer length */
4738 if(inputParameters)
4739 {
4740 /* Calculate the frames from the user's value - add a bit to round up */
4741 stream->capture.framesPerBuffer = (unsigned long)((inputParameters->suggestedLatency*sampleRate)+0.0001);
4742 if(stream->capture.framesPerBuffer > (unsigned long)sampleRate)
4743 { /* Upper limit is 1 second */
4744 stream->capture.framesPerBuffer = (unsigned long)sampleRate;
4745 }
4746 else if(stream->capture.framesPerBuffer < stream->capture.pPin->frameSize)
4747 {
4748 stream->capture.framesPerBuffer = stream->capture.pPin->frameSize;
4749 }
4750 PA_DEBUG(("Input frames chosen:%ld\n",stream->capture.framesPerBuffer));
4751
4752 /* Setup number of packets to use */
4753 stream->capture.noOfPackets = 2;
4754
4755 if (inputParameters->hostApiSpecificStreamInfo)
4756 {
4757 PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)inputParameters->hostApiSpecificStreamInfo;
4758
4759 if (stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic &&
4760 pInfo->noOfPackets != 0)
4761 {
4762 stream->capture.noOfPackets = pInfo->noOfPackets;
4763 }
4764 }
4765 }
4766
4767 if(outputParameters)
4768 {
4769 /* Calculate the frames from the user's value - add a bit to round up */
4770 stream->render.framesPerBuffer = (unsigned long)((outputParameters->suggestedLatency*sampleRate)+0.0001);
4771 if(stream->render.framesPerBuffer > (unsigned long)sampleRate)
4772 { /* Upper limit is 1 second */
4773 stream->render.framesPerBuffer = (unsigned long)sampleRate;
4774 }
4775 else if(stream->render.framesPerBuffer < stream->render.pPin->frameSize)
4776 {
4777 stream->render.framesPerBuffer = stream->render.pPin->frameSize;
4778 }
4779 PA_DEBUG(("Output frames chosen:%ld\n",stream->render.framesPerBuffer));
4780
4781 /* Setup number of packets to use */
4782 stream->render.noOfPackets = 2;
4783
4784 if (outputParameters->hostApiSpecificStreamInfo)
4785 {
4786 PaWinWDMKSInfo* pInfo = (PaWinWDMKSInfo*)outputParameters->hostApiSpecificStreamInfo;
4787
4788 if (stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic &&
4789 pInfo->noOfPackets != 0)
4790 {
4791 stream->render.noOfPackets = pInfo->noOfPackets;
4792 }
4793 }
4794 }
4795
4796 /* Host buffer size is bound to the largest of the input and output frame sizes */
4797 result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
4798 stream->userInputChannels, inputSampleFormat, hostInputSampleFormat,
4799 stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat,
4800 sampleRate, streamFlags, framesPerUserBuffer,
4801 max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer),
4802 paUtilBoundedHostBufferSize,
4803 streamCallback, userData );
4804 if( result != paNoError )
4805 {
4806 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",
4807 stream->userInputChannels, inputSampleFormat, hostInputSampleFormat,
4808 stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat,
4809 sampleRate, streamFlags, framesPerUserBuffer,
4810 max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer));
4811 goto error;
4812 }
4813
4814 /* Allocate/get all the buffers for host I/O */
4815 if (stream->userInputChannels > 0)
4816 {
4817 stream->streamRepresentation.streamInfo.inputLatency = stream->capture.framesPerBuffer / sampleRate;
4818
4819 switch (stream->capture.pPin->parentFilter->devInfo.streamingType)
4820 {
4821 case Type_kWaveCyclic:
4822 {
4823 unsigned size = stream->capture.noOfPackets * stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;
4824 /* Allocate input host buffer */
4825 stream->capture.hostBuffer = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, size);
4826 PA_DEBUG(("Input buffer allocated (size = %u)\n", size));
4827 if( !stream->capture.hostBuffer )
4828 {
4829 PA_DEBUG(("Cannot allocate host input buffer!\n"));
4830 PaWinWDM_SetLastErrorInfo(paInsufficientMemory, "Failed to allocate input buffer");
4831 result = paInsufficientMemory;
4832 goto error;
4833 }
4834 stream->capture.hostBufferSize = size;
4835 PA_DEBUG(("Input buffer start = %p (size=%u)\n",stream->capture.hostBuffer, stream->capture.hostBufferSize));
4836 stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveCyclic;
4837 stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveCyclic;
4838 }
4839 break;
4840 case Type_kWaveRT:
4841 {
4842 const DWORD dwTotalSize = 2 * stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;
4843 DWORD dwRequestedSize = dwTotalSize;
4844 BOOL bCallMemoryBarrier = FALSE;
4845 ULONG hwFifoLatency = 0;
4846 ULONG dummy;
4847 result = PinGetBuffer(stream->capture.pPin, (void**)&stream->capture.hostBuffer, &dwRequestedSize, &bCallMemoryBarrier);
4848 if (!result)
4849 {
4850 PA_DEBUG(("Input buffer start = %p, size = %u\n", stream->capture.hostBuffer, dwRequestedSize));
4851 if (dwRequestedSize != dwTotalSize)
4852 {
4853 PA_DEBUG(("Buffer length changed by driver from %u to %u !\n", dwTotalSize, dwRequestedSize));
4854 /* Recalculate to what the driver has given us */
4855 stream->capture.framesPerBuffer = dwRequestedSize / (2 * stream->capture.bytesPerFrame);
4856 }
4857 stream->capture.hostBufferSize = dwRequestedSize;
4858
4859 if (stream->capture.pPin->pinKsSubType == SubType_kPolled)
4860 {
4861 stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveRTPolled;
4862 stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveRTPolled;
4863 }
4864 else
4865 {
4866 stream->capture.pPin->fnEventHandler = PaPinCaptureEventHandler_WaveRTEvent;
4867 stream->capture.pPin->fnSubmitHandler = PaPinCaptureSubmitHandler_WaveRTEvent;
4868 }
4869
4870 stream->capture.pPin->fnMemBarrier = bCallMemoryBarrier ? MemoryBarrierRead : MemoryBarrierDummy;
4871 }
4872 else
4873 {
4874 PA_DEBUG(("Failed to get input buffer (WaveRT)\n"));
4875 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to get input buffer (WaveRT)");
4876 result = paUnanticipatedHostError;
4877 goto error;
4878 }
4879
4880 /* Get latency */
4881 result = PinGetHwLatency(stream->capture.pPin, &hwFifoLatency, &dummy, &dummy);
4882 if (result == paNoError)
4883 {
4884 stream->capture.pPin->hwLatency = hwFifoLatency;
4885
4886 /* Add HW latency into total input latency */
4887 stream->streamRepresentation.streamInfo.inputLatency += ((hwFifoLatency / stream->capture.bytesPerFrame) / sampleRate);
4888 }
4889 else
4890 {
4891 PA_DEBUG(("Failed to get size of FIFO hardware buffer (is set to zero)\n"));
4892 stream->capture.pPin->hwLatency = 0;
4893 }
4894 }
4895 break;
4896 default:
4897 /* Undefined wave type!! */
4898 assert(0);
4899 result = paInternalError;
4900 PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
4901 goto error;
4902 }
4903 }
4904 else
4905 {
4906 stream->capture.hostBuffer = 0;
4907 }
4908
4909 if (stream->userOutputChannels > 0)
4910 {
4911 stream->streamRepresentation.streamInfo.outputLatency = stream->render.framesPerBuffer / sampleRate;
4912
4913 switch (stream->render.pPin->parentFilter->devInfo.streamingType)
4914 {
4915 case Type_kWaveCyclic:
4916 {
4917 unsigned size = stream->render.noOfPackets * stream->render.framesPerBuffer * stream->render.bytesPerFrame;
4918 /* Allocate output device buffer */
4919 stream->render.hostBuffer = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, size);
4920 PA_DEBUG(("Output buffer allocated (size = %u)\n", size));
4921 if( !stream->render.hostBuffer )
4922 {
4923 PA_DEBUG(("Cannot allocate host output buffer!\n"));
4924 PaWinWDM_SetLastErrorInfo(paInsufficientMemory, "Failed to allocate output buffer");
4925 result = paInsufficientMemory;
4926 goto error;
4927 }
4928 stream->render.hostBufferSize = size;
4929 PA_DEBUG(("Output buffer start = %p (size=%u)\n",stream->render.hostBuffer, stream->render.hostBufferSize));
4930
4931 stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveCyclic;
4932 stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveCyclic;
4933 }
4934 break;
4935 case Type_kWaveRT:
4936 {
4937 const DWORD dwTotalSize = 2 * stream->render.framesPerBuffer * stream->render.bytesPerFrame;
4938 DWORD dwRequestedSize = dwTotalSize;
4939 BOOL bCallMemoryBarrier = FALSE;
4940 ULONG hwFifoLatency = 0;
4941 ULONG dummy;
4942 result = PinGetBuffer(stream->render.pPin, (void**)&stream->render.hostBuffer, &dwRequestedSize, &bCallMemoryBarrier);
4943 if (!result)
4944 {
4945 PA_DEBUG(("Output buffer start = %p, size = %u, membarrier = %u\n", stream->render.hostBuffer, dwRequestedSize, bCallMemoryBarrier));
4946 if (dwRequestedSize != dwTotalSize)
4947 {
4948 PA_DEBUG(("Buffer length changed by driver from %u to %u !\n", dwTotalSize, dwRequestedSize));
4949 /* Recalculate to what the driver has given us */
4950 stream->render.framesPerBuffer = dwRequestedSize / (2 * stream->render.bytesPerFrame);
4951 }
4952 stream->render.hostBufferSize = dwRequestedSize;
4953
4954 if (stream->render.pPin->pinKsSubType == SubType_kPolled)
4955 {
4956 stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveRTPolled;
4957 stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveRTPolled;
4958 }
4959 else
4960 {
4961 stream->render.pPin->fnEventHandler = PaPinRenderEventHandler_WaveRTEvent;
4962 stream->render.pPin->fnSubmitHandler = PaPinRenderSubmitHandler_WaveRTEvent;
4963 }
4964
4965 stream->render.pPin->fnMemBarrier = bCallMemoryBarrier ? MemoryBarrierWrite : MemoryBarrierDummy;
4966 }
4967 else
4968 {
4969 PA_DEBUG(("Failed to get output buffer (with notification)\n"));
4970 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to get output buffer (with notification)");
4971 result = paUnanticipatedHostError;
4972 goto error;
4973 }
4974
4975 /* Get latency */
4976 result = PinGetHwLatency(stream->render.pPin, &hwFifoLatency, &dummy, &dummy);
4977 if (result == paNoError)
4978 {
4979 stream->render.pPin->hwLatency = hwFifoLatency;
4980
4981 /* Add HW latency into total output latency */
4982 stream->streamRepresentation.streamInfo.outputLatency += ((hwFifoLatency / stream->render.bytesPerFrame) / sampleRate);
4983 }
4984 else
4985 {
4986 PA_DEBUG(("Failed to get size of FIFO hardware buffer (is set to zero)\n"));
4987 stream->render.pPin->hwLatency = 0;
4988 }
4989 }
4990 break;
4991 default:
4992 /* Undefined wave type!! */
4993 assert(0);
4994 result = paInternalError;
4995 PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
4996 goto error;
4997 }
4998 }
4999 else
5000 {
5001 stream->render.hostBuffer = 0;
5002 }
5003
5004 stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
5005
5006 PA_DEBUG(("BytesPerInputFrame = %d\n",stream->capture.bytesPerFrame));
5007 PA_DEBUG(("BytesPerOutputFrame = %d\n",stream->render.bytesPerFrame));
5008
5009 /* memset(stream->hostBuffer,0,size); */
5010
5011 /* Abort */
5012 stream->eventAbort = CreateEvent(NULL, TRUE, FALSE, NULL);
5013 if (stream->eventAbort == 0)
5014 {
5015 result = paInsufficientMemory;
5016 goto error;
5017 }
5018 stream->eventStreamStart[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
5019 if (stream->eventStreamStart[0] == 0)
5020 {
5021 result = paInsufficientMemory;
5022 goto error;
5023 }
5024 stream->eventStreamStart[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
5025 if (stream->eventStreamStart[1] == 0)
5026 {
5027 result = paInsufficientMemory;
5028 goto error;
5029 }
5030
5031 if(stream->userInputChannels > 0)
5032 {
5033 const unsigned bufferSizeInBytes = stream->capture.framesPerBuffer * stream->capture.bytesPerFrame;
5034 const unsigned ringBufferFrameSize = NextPowerOf2( 1024 + 2 * max(stream->capture.framesPerBuffer, stream->render.framesPerBuffer) );
5035
5036 stream->capture.events = (HANDLE*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->capture.noOfPackets * sizeof(HANDLE));
5037 if (stream->capture.events == NULL)
5038 {
5039 result = paInsufficientMemory;
5040 goto error;
5041 }
5042
5043 stream->capture.packets = (DATAPACKET*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->capture.noOfPackets * sizeof(DATAPACKET));
5044 if (stream->capture.packets == NULL)
5045 {
5046 result = paInsufficientMemory;
5047 goto error;
5048 }
5049
5050 switch(stream->capture.pPin->parentFilter->devInfo.streamingType)
5051 {
5052 case Type_kWaveCyclic:
5053 {
5054 /* WaveCyclic case */
5055 unsigned i;
5056 for (i = 0; i < stream->capture.noOfPackets; ++i)
5057 {
5058 /* Set up the packets */
5059 DATAPACKET *p = stream->capture.packets + i;
5060
5061 /* Record event */
5062 stream->capture.events[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
5063
5064 p->Signal.hEvent = stream->capture.events[i];
5065 p->Header.Data = stream->capture.hostBuffer + (i*bufferSizeInBytes);
5066 p->Header.FrameExtent = bufferSizeInBytes;
5067 p->Header.DataUsed = 0;
5068 p->Header.Size = sizeof(p->Header);
5069 p->Header.PresentationTime.Numerator = 1;
5070 p->Header.PresentationTime.Denominator = 1;
5071 }
5072 }
5073 break;
5074 case Type_kWaveRT:
5075 {
5076 /* Set up the "packets" */
5077 DATAPACKET *p = stream->capture.packets + 0;
5078
5079 /* Record event: WaveRT has a single event for 2 notification per buffer */
5080 stream->capture.events[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
5081
5082 p->Header.Data = stream->capture.hostBuffer;
5083 p->Header.FrameExtent = bufferSizeInBytes;
5084 p->Header.DataUsed = 0;
5085 p->Header.Size = sizeof(p->Header);
5086 p->Header.PresentationTime.Numerator = 1;
5087 p->Header.PresentationTime.Denominator = 1;
5088
5089 ++p;
5090 p->Header.Data = stream->capture.hostBuffer + bufferSizeInBytes;
5091 p->Header.FrameExtent = bufferSizeInBytes;
5092 p->Header.DataUsed = 0;
5093 p->Header.Size = sizeof(p->Header);
5094 p->Header.PresentationTime.Numerator = 1;
5095 p->Header.PresentationTime.Denominator = 1;
5096
5097 if (stream->capture.pPin->pinKsSubType == SubType_kNotification)
5098 {
5099 result = PinRegisterNotificationHandle(stream->capture.pPin, stream->capture.events[0]);
5100
5101 if (result != paNoError)
5102 {
5103 PA_DEBUG(("Failed to register capture notification handle\n"));
5104 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to register capture notification handle");
5105 result = paUnanticipatedHostError;
5106 goto error;
5107 }
5108 }
5109
5110 result = PinRegisterPositionRegister(stream->capture.pPin);
5111
5112 if (result != paNoError)
5113 {
5114 unsigned long pos = 0xdeadc0de;
5115 PA_DEBUG(("Failed to register capture position register, using PinGetAudioPositionViaIOCTLWrite\n"));
5116 stream->capture.pPin->fnAudioPosition = PinGetAudioPositionViaIOCTLWrite;
5117 /* Test position function */
5118 result = (stream->capture.pPin->fnAudioPosition)(stream->capture.pPin, &pos);
5119 if (result != paNoError || pos != 0x0)
5120 {
5121 PA_DEBUG(("Failed to read capture position register (IOCTL)\n"));
5122 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to read capture position register (IOCTL)");
5123 result = paUnanticipatedHostError;
5124 goto error;
5125 }
5126 }
5127 else
5128 {
5129 stream->capture.pPin->fnAudioPosition = PinGetAudioPositionMemoryMapped;
5130 }
5131 }
5132 break;
5133 default:
5134 /* Undefined wave type!! */
5135 assert(0);
5136 result = paInternalError;
5137 PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
5138 goto error;
5139 }
5140
5141 /* Setup the input ring buffer here */
5142 stream->ringBufferData = (char*)PaUtil_GroupAllocateMemory(stream->allocGroup, ringBufferFrameSize * stream->capture.bytesPerFrame);
5143 if (stream->ringBufferData == NULL)
5144 {
5145 result = paInsufficientMemory;
5146 goto error;
5147 }
5148 PaUtil_InitializeRingBuffer(&stream->ringBuffer, stream->capture.bytesPerFrame, ringBufferFrameSize, stream->ringBufferData);
5149 }
5150 if(stream->userOutputChannels > 0)
5151 {
5152 const unsigned bufferSizeInBytes = stream->render.framesPerBuffer * stream->render.bytesPerFrame;
5153
5154 stream->render.events = (HANDLE*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->render.noOfPackets * sizeof(HANDLE));
5155 if (stream->render.events == NULL)
5156 {
5157 result = paInsufficientMemory;
5158 goto error;
5159 }
5160
5161 stream->render.packets = (DATAPACKET*)PaUtil_GroupAllocateMemory(stream->allocGroup, stream->render.noOfPackets * sizeof(DATAPACKET));
5162 if (stream->render.packets == NULL)
5163 {
5164 result = paInsufficientMemory;
5165 goto error;
5166 }
5167
5168 switch(stream->render.pPin->parentFilter->devInfo.streamingType)
5169 {
5170 case Type_kWaveCyclic:
5171 {
5172 /* WaveCyclic case */
5173 unsigned i;
5174 for (i = 0; i < stream->render.noOfPackets; ++i)
5175 {
5176 /* Set up the packets */
5177 DATAPACKET *p = stream->render.packets + i;
5178
5179 /* Playback event */
5180 stream->render.events[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
5181
5182 /* In this case, we just use the packets as ptr to the device buffer */
5183 p->Signal.hEvent = stream->render.events[i];
5184 p->Header.Data = stream->render.hostBuffer + (i*bufferSizeInBytes);
5185 p->Header.FrameExtent = bufferSizeInBytes;
5186 p->Header.DataUsed = bufferSizeInBytes;
5187 p->Header.Size = sizeof(p->Header);
5188 p->Header.PresentationTime.Numerator = 1;
5189 p->Header.PresentationTime.Denominator = 1;
5190 }
5191 }
5192 break;
5193 case Type_kWaveRT:
5194 {
5195 /* WaveRT case */
5196
5197 /* Set up the "packets" */
5198 DATAPACKET *p = stream->render.packets;
5199
5200 /* The only playback event */
5201 stream->render.events[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
5202
5203 /* In this case, we just use the packets as ptr to the device buffer */
5204 p->Header.Data = stream->render.hostBuffer;
5205 p->Header.FrameExtent = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
5206 p->Header.DataUsed = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
5207 p->Header.Size = sizeof(p->Header);
5208 p->Header.PresentationTime.Numerator = 1;
5209 p->Header.PresentationTime.Denominator = 1;
5210
5211 ++p;
5212 p->Header.Data = stream->render.hostBuffer + stream->render.framesPerBuffer*stream->render.bytesPerFrame;
5213 p->Header.FrameExtent = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
5214 p->Header.DataUsed = stream->render.framesPerBuffer*stream->render.bytesPerFrame;
5215 p->Header.Size = sizeof(p->Header);
5216 p->Header.PresentationTime.Numerator = 1;
5217 p->Header.PresentationTime.Denominator = 1;
5218
5219 if (stream->render.pPin->pinKsSubType == SubType_kNotification)
5220 {
5221 result = PinRegisterNotificationHandle(stream->render.pPin, stream->render.events[0]);
5222
5223 if (result != paNoError)
5224 {
5225 PA_DEBUG(("Failed to register rendering notification handle\n"));
5226 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to register rendering notification handle");
5227 result = paUnanticipatedHostError;
5228 goto error;
5229 }
5230 }
5231
5232 result = PinRegisterPositionRegister(stream->render.pPin);
5233
5234 if (result != paNoError)
5235 {
5236 unsigned long pos = 0xdeadc0de;
5237 PA_DEBUG(("Failed to register rendering position register, using PinGetAudioPositionViaIOCTLRead\n"));
5238 stream->render.pPin->fnAudioPosition = PinGetAudioPositionViaIOCTLRead;
5239 /* Test position function */
5240 result = (stream->render.pPin->fnAudioPosition)(stream->render.pPin, &pos);
5241 if (result != paNoError || pos != 0x0)
5242 {
5243 PA_DEBUG(("Failed to read render position register (IOCTL)\n"));
5244 PaWinWDM_SetLastErrorInfo(paUnanticipatedHostError, "Failed to read render position register (IOCTL)");
5245 result = paUnanticipatedHostError;
5246 goto error;
5247 }
5248 }
5249 else
5250 {
5251 stream->render.pPin->fnAudioPosition = PinGetAudioPositionMemoryMapped;
5252 }
5253 }
5254 break;
5255 default:
5256 /* Undefined wave type!! */
5257 assert(0);
5258 result = paInternalError;
5259 PaWinWDM_SetLastErrorInfo(result, "Wave type %u ??", stream->capture.pPin->parentFilter->devInfo.streamingType);
5260 goto error;
5261 }
5262 }
5263
5264 stream->streamStarted = 0;
5265 stream->streamActive = 0;
5266 stream->streamStop = 0;
5267 stream->streamAbort = 0;
5268 stream->streamFlags = streamFlags;
5269 stream->oldProcessPriority = REALTIME_PRIORITY_CLASS;
5270
5271 /* Increase ref count on filters in use, so that a CommitDeviceInfos won't delete them */
5272 if (stream->capture.pPin != 0)
5273 {
5274 FilterAddRef(stream->capture.pPin->parentFilter);
5275 }
5276 if (stream->render.pPin != 0)
5277 {
5278 FilterAddRef(stream->render.pPin->parentFilter);
5279 }
5280
5281 /* Ok, now update our host API specific stream info */
5282 if (stream->userInputChannels)
5283 {
5284 PaWinWdmDeviceInfo *pDeviceInfo = (PaWinWdmDeviceInfo*)wdmHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
5285
5286 stream->hostApiStreamInfo.input.device = Pa_HostApiDeviceIndexToDeviceIndex(Pa_HostApiTypeIdToHostApiIndex(paWDMKS), inputParameters->device);
5287 stream->hostApiStreamInfo.input.channels = stream->deviceInputChannels;
5288 stream->hostApiStreamInfo.input.muxNodeId = -1;
5289 if (stream->capture.pPin->inputs)
5290 {
5291 stream->hostApiStreamInfo.input.muxNodeId = stream->capture.pPin->inputs[pDeviceInfo->muxPosition]->muxNodeId;
5292 }
5293 stream->hostApiStreamInfo.input.endpointPinId = pDeviceInfo->endpointPinId;
5294 stream->hostApiStreamInfo.input.framesPerHostBuffer = stream->capture.framesPerBuffer;
5295 stream->hostApiStreamInfo.input.streamingSubType = stream->capture.pPin->pinKsSubType;
5296 }
5297 else
5298 {
5299 stream->hostApiStreamInfo.input.device = paNoDevice;
5300 }
5301 if (stream->userOutputChannels)
5302 {
5303 stream->hostApiStreamInfo.output.device = Pa_HostApiDeviceIndexToDeviceIndex(Pa_HostApiTypeIdToHostApiIndex(paWDMKS), outputParameters->device);
5304 stream->hostApiStreamInfo.output.channels = stream->deviceOutputChannels;
5305 stream->hostApiStreamInfo.output.framesPerHostBuffer = stream->render.framesPerBuffer;
5306 stream->hostApiStreamInfo.output.endpointPinId = stream->render.pPin->endpointPinId;
5307 stream->hostApiStreamInfo.output.streamingSubType = stream->render.pPin->pinKsSubType;
5308 }
5309 else
5310 {
5311 stream->hostApiStreamInfo.output.device = paNoDevice;
5312 }
5313 /*stream->streamRepresentation.streamInfo.hostApiTypeId = paWDMKS;
5314 stream->streamRepresentation.streamInfo.hostApiSpecificStreamInfo = &stream->hostApiStreamInfo;*/
5315 stream->streamRepresentation.streamInfo.structVersion = 2;
5316
5317 *s = (PaStream*)stream;
5318
5319 PA_LOGL_;
5320 return result;
5321
5322 occupied:
5323 /* Ok, someone else is hogging the pin, bail out */
5324 assert (result == paDeviceUnavailable);
5325 PaWinWDM_SetLastErrorInfo(result, "Device is occupied");
5326
5327 error:
5328 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
5329
5330 CloseStreamEvents(stream);
5331
5332 if (stream->allocGroup)
5333 {
5334 PaUtil_FreeAllAllocations(stream->allocGroup);
5335 PaUtil_DestroyAllocationGroup(stream->allocGroup);
5336 stream->allocGroup = 0;
5337 }
5338
5339 if(stream->render.pPin)
5340 PinClose(stream->render.pPin);
5341 if(stream->capture.pPin)
5342 PinClose(stream->capture.pPin);
5343
5344 PaUtil_FreeMemory( stream );
5345
5346 PA_LOGL_;
5347 return result;
5348 }
5349
5350 /*
5351 When CloseStream() is called, the multi-api layer ensures that
5352 the stream has already been stopped or aborted.
5353 */
5354 static PaError CloseStream( PaStream* s )
5355 {
5356 PaError result = paNoError;
5357 PaWinWdmStream *stream = (PaWinWdmStream*)s;
5358
5359 PA_LOGE_;
5360
5361 assert(!stream->streamStarted);
5362 assert(!stream->streamActive);
5363
5364 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
5365 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
5366
5367 CloseStreamEvents(stream);
5368
5369 if (stream->allocGroup)
5370 {
5371 PaUtil_FreeAllAllocations(stream->allocGroup);
5372 PaUtil_DestroyAllocationGroup(stream->allocGroup);
5373 stream->allocGroup = 0;
5374 }
5375
5376 if(stream->render.pPin)
5377 {
5378 PinClose(stream->render.pPin);
5379 }
5380 if(stream->capture.pPin)
5381 {
5382 PinClose(stream->capture.pPin);
5383 }
5384
5385 if (stream->render.pPin)
5386 {
5387 FilterFree(stream->render.pPin->parentFilter);
5388 }
5389 if (stream->capture.pPin)
5390 {
5391 FilterFree(stream->capture.pPin->parentFilter);
5392 }
5393
5394 PaUtil_FreeMemory( stream );
5395
5396 PA_LOGL_;
5397 return result;
5398 }
5399
5400 /*
5401 Write the supplied packet to the pin
5402 Asynchronous
5403 Should return paNoError on success
5404 */
5405 static PaError PinWrite(HANDLE h, DATAPACKET* p)
5406 {
5407 PaError result = paNoError;
5408 unsigned long cbReturned = 0;
5409 BOOL fRes = DeviceIoControl(h,
5410 IOCTL_KS_WRITE_STREAM,
5411 NULL,
5412 0,
5413 &p->Header,
5414 p->Header.Size,
5415 &cbReturned,
5416 &p->Signal);
5417 if (!fRes)
5418 {
5419 unsigned long error = GetLastError();
5420 if (error != ERROR_IO_PENDING)
5421 {
5422 result = paInternalError;
5423 }
5424 }
5425 return result;
5426 }
5427
5428 /*
5429 Read to the supplied packet from the pin
5430 Asynchronous
5431 Should return paNoError on success
5432 */
5433 static PaError PinRead(HANDLE h, DATAPACKET* p)
5434 {
5435 PaError result = paNoError;
5436 unsigned long cbReturned = 0;
5437 BOOL fRes = DeviceIoControl(h,
5438 IOCTL_KS_READ_STREAM,
5439 NULL,
5440 0,
5441 &p->Header,
5442 p->Header.Size,
5443 &cbReturned,
5444 &p->Signal);
5445 if (!fRes)
5446 {
5447 unsigned long error = GetLastError();
5448 if (error != ERROR_IO_PENDING)
5449 {
5450 result = paInternalError;
5451 }
5452 }
5453 return result;
5454 }
5455
5456 /*
5457 Copy the first interleaved channel of 16 bit data to the other channels
5458 */
5459 static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples)
5460 {
5461 unsigned short* data = (unsigned short*)buffer;
5462 int channel;
5463 unsigned short sourceSample;
5464 while( samples-- )
5465 {
5466 sourceSample = *data++;
5467 channel = channels-1;
5468 while( channel-- )
5469 {
5470 *data++ = sourceSample;
5471 }
5472 }
5473 }
5474
5475 /*
5476 Copy the first interleaved channel of 24 bit data to the other channels
5477 */
5478 static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples)
5479 {
5480 unsigned char* data = (unsigned char*)buffer;
5481 int channel;
5482 unsigned char sourceSample[3];
5483 while( samples-- )
5484 {
5485 sourceSample[0] = data[0];
5486 sourceSample[1] = data[1];
5487 sourceSample[2] = data[2];
5488 data += 3;
5489 channel = channels-1;
5490 while( channel-- )
5491 {
5492 data[0] = sourceSample[0];
5493 data[1] = sourceSample[1];
5494 data[2] = sourceSample[2];
5495 data += 3;
5496 }
5497 }
5498 }
5499
5500 /*
5501 Copy the first interleaved channel of 32 bit data to the other channels
5502 */
5503 static void DuplicateFirstChannelInt32(void* buffer, int channels, int samples)
5504 {
5505 unsigned long* data = (unsigned long*)buffer;
5506 int channel;
5507 unsigned long sourceSample;
5508 while( samples-- )
5509 {
5510 sourceSample = *data++;
5511 channel = channels-1;
5512 while( channel-- )
5513 {
5514 *data++ = sourceSample;
5515 }
5516 }
5517 }
5518
5519 /*
5520 Increase the priority of the calling thread to RT
5521 */
5522 static HANDLE BumpThreadPriority()
5523 {
5524 HANDLE hThread = GetCurrentThread();
5525 DWORD dwTask = 0;
5526 HANDLE hAVRT = NULL;
5527
5528 /* If we have access to AVRT.DLL (Vista and later), use it */
5529 if (paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics != NULL)
5530 {
5531 hAVRT = paWinWDMKSAvRtEntryPoints.AvSetMmThreadCharacteristics("Pro Audio", &dwTask);
5532 if (hAVRT != NULL && hAVRT != INVALID_HANDLE_VALUE)
5533 {
5534 BOOL bret = paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority(hAVRT, PA_AVRT_PRIORITY_CRITICAL);
5535 if (!bret)
5536 {
5537 PA_DEBUG(("Set mm thread prio to critical failed!\n"));
5538 }
5539 else
5540 {
5541 return hAVRT;
5542 }
5543 }
5544 else
5545 {
5546 PA_DEBUG(("Set mm thread characteristic to 'Pro Audio' failed, reverting to SetThreadPriority\n"));
5547 }
5548 }
5549
5550 /* For XP and earlier, or if AvSetMmThreadCharacteristics fails (MMCSS disabled ?) */
5551 if (timeBeginPeriod(1) != TIMERR_NOERROR) {
5552 PA_DEBUG(("timeBeginPeriod(1) failed!\n"));
5553 }
5554
5555 if (!SetThreadPriority(hThread, THREAD_PRIORITY_TIME_CRITICAL)) {
5556 PA_DEBUG(("SetThreadPriority failed!\n"));
5557 }
5558
5559 return hAVRT;
5560 }
5561
5562 /*
5563 Decrease the priority of the calling thread to normal
5564 */
5565 static void DropThreadPriority(HANDLE hAVRT)
5566 {
5567 HANDLE hThread = GetCurrentThread();
5568
5569 if (hAVRT != NULL)
5570 {
5571 paWinWDMKSAvRtEntryPoints.AvSetMmThreadPriority(hAVRT, PA_AVRT_PRIORITY_NORMAL);
5572 paWinWDMKSAvRtEntryPoints.AvRevertMmThreadCharacteristics(hAVRT);
5573 return;
5574 }
5575
5576 SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL);
5577 timeEndPeriod(1);
5578 }
5579
5580 static PaError PreparePinForStart(PaWinWdmPin* pin)
5581 {
5582 PaError result;
5583 result = PinSetState(pin, KSSTATE_ACQUIRE);
5584 if (result != paNoError)
5585 {
5586 goto error;
5587 }
5588 result = PinSetState(pin, KSSTATE_PAUSE);
5589 if (result != paNoError)
5590 {
5591 goto error;
5592 }
5593 return result;
5594
5595 error:
5596 PinSetState(pin, KSSTATE_STOP);
5597 return result;
5598 }
5599
5600 static PaError PreparePinsForStart(PaProcessThreadInfo* pInfo)
5601 {
5602 PaError result = paNoError;
5603 /* Submit buffers */
5604 if (pInfo->stream->capture.pPin)
5605 {
5606 if ((result = PreparePinForStart(pInfo->stream->capture.pPin)) != paNoError)
5607 {
5608 goto error;
5609 }
5610
5611 if (pInfo->stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
5612 {
5613 unsigned i;
5614 for(i=0; i < pInfo->stream->capture.noOfPackets; ++i)
5615 {
5616 if ((result = PinRead(pInfo->stream->capture.pPin->handle, pInfo->stream->capture.packets + i)) != paNoError)
5617 {
5618 goto error;
5619 }
5620 ++pInfo->pending;
5621 }
5622 }
5623 else
5624 {
5625 pInfo->pending = 2;
5626 }
5627 }
5628
5629 if(pInfo->stream->render.pPin)
5630 {
5631 if ((result = PreparePinForStart(pInfo->stream->render.pPin)) != paNoError)
5632 {
5633 goto error;
5634 }
5635
5636 pInfo->priming += pInfo->stream->render.noOfPackets;
5637 ++pInfo->pending;
5638 SetEvent(pInfo->stream->render.events[0]);
5639 if (pInfo->stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
5640 {
5641 unsigned i;
5642 for(i=1; i < pInfo->stream->render.noOfPackets; ++i)
5643 {
5644 SetEvent(pInfo->stream->render.events[i]);
5645 ++pInfo->pending;
5646 }
5647 }
5648 }
5649
5650 error:
5651 PA_DEBUG(("PreparePinsForStart = %d\n", result));
5652 return result;
5653 }
5654
5655 static PaError StartPin(PaWinWdmPin* pin)
5656 {
5657 return PinSetState(pin, KSSTATE_RUN);
5658 }
5659
5660 static PaError StartPins(PaProcessThreadInfo* pInfo)
5661 {
5662 PaError result = paNoError;
5663 /* Start the pins as synced as possible */
5664 if (pInfo->stream->capture.pPin)
5665 {
5666 result = StartPin(pInfo->stream->capture.pPin);
5667 }
5668 if(pInfo->stream->render.pPin)
5669 {
5670 result = StartPin(pInfo->stream->render.pPin);
5671 }
5672 PA_DEBUG(("StartPins = %d\n", result));
5673 return result;
5674 }
5675
5676
5677 static PaError StopPin(PaWinWdmPin* pin)
5678 {
5679 PinSetState(pin, KSSTATE_PAUSE);
5680 PinSetState(pin, KSSTATE_STOP);
5681 return paNoError;
5682 }
5683
5684
5685 static PaError StopPins(PaProcessThreadInfo* pInfo)
5686 {
5687 PaError result = paNoError;
5688 if(pInfo->stream->render.pPin)
5689 {
5690 StopPin(pInfo->stream->render.pPin);
5691 }
5692 if(pInfo->stream->capture.pPin)
5693 {
5694 StopPin(pInfo->stream->capture.pPin);
5695 }
5696 return result;
5697 }
5698
5699 typedef void (*TSetInputFrameCount)(PaUtilBufferProcessor*, unsigned long);
5700 typedef void (*TSetInputChannel)(PaUtilBufferProcessor*, unsigned int, void *, unsigned int);
5701 static const TSetInputFrameCount fnSetInputFrameCount[2] = { PaUtil_SetInputFrameCount, PaUtil_Set2ndInputFrameCount };
5702 static const TSetInputChannel fnSetInputChannel[2] = { PaUtil_SetInputChannel, PaUtil_Set2ndInputChannel };
5703
5704 static PaError PaDoProcessing(PaProcessThreadInfo* pInfo)
5705 {
5706 PaError result = paNoError;
5707 int i, framesProcessed = 0, doChannelCopy = 0;
5708 ring_buffer_size_t inputFramesAvailable = PaUtil_GetRingBufferReadAvailable(&pInfo->stream->ringBuffer);
5709
5710 /* Do necessary buffer processing (which will invoke user callback if necessary) */
5711 if (pInfo->cbResult == paContinue &&
5712 (pInfo->renderHead != pInfo->renderTail || inputFramesAvailable))
5713 {
5714 unsigned processFullDuplex = pInfo->stream->capture.pPin && pInfo->stream->render.pPin && (!pInfo->priming);
5715
5716 PA_HP_TRACE((pInfo->stream->hLog, "DoProcessing: InputFrames=%u", inputFramesAvailable));
5717
5718 PaUtil_BeginCpuLoadMeasurement( &pInfo->stream->cpuLoadMeasurer );
5719
5720 pInfo->ti.currentTime = PaUtil_GetTime();
5721
5722 PaUtil_BeginBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->ti, pInfo->underover);
5723 pInfo->underover = 0; /* Reset the (under|over)flow status */
5724
5725 if (pInfo->renderTail != pInfo->renderHead)
5726 {
5727 DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;
5728
5729 assert(packet != 0);
5730 assert(packet->Header.Data != 0);
5731
5732 PaUtil_SetOutputFrameCount(&pInfo->stream->bufferProcessor, pInfo->stream->render.framesPerBuffer);
5733
5734 for(i=0;i<pInfo->stream->userOutputChannels;i++)
5735 {
5736 /* Only write the user output channels. Leave the rest blank */
5737 PaUtil_SetOutputChannel(&pInfo->stream->bufferProcessor,
5738 i,
5739 ((unsigned char*)(packet->Header.Data))+(i*pInfo->stream->render.bytesPerSample),
5740 pInfo->stream->deviceOutputChannels);
5741 }
5742
5743 /* We will do a copy to the other channels after the data has been written */
5744 doChannelCopy = ( pInfo->stream->userOutputChannels == 1 );
5745 }
5746
5747 if (inputFramesAvailable && (!pInfo->stream->userOutputChannels || inputFramesAvailable >= (int)pInfo->stream->render.framesPerBuffer))
5748 {
5749 unsigned wrapCntr = 0;
5750 void* data[2] = {0};
5751 ring_buffer_size_t size[2] = {0};
5752
5753 /* If full-duplex, we just extract output buffer number of frames */
5754 if (pInfo->stream->userOutputChannels)
5755 {
5756 inputFramesAvailable = min(inputFramesAvailable, (int)pInfo->stream->render.framesPerBuffer);
5757 }
5758
5759 inputFramesAvailable = PaUtil_GetRingBufferReadRegions(&pInfo->stream->ringBuffer,
5760 inputFramesAvailable,
5761 &data[0],
5762 &size[0],
5763 &data[1],
5764 &size[1]);
5765
5766 for (wrapCntr = 0; wrapCntr < 2; ++wrapCntr)
5767 {
5768 if (size[wrapCntr] == 0)
5769 break;
5770
5771 fnSetInputFrameCount[wrapCntr](&pInfo->stream->bufferProcessor, size[wrapCntr]);
5772 for(i=0;i<pInfo->stream->userInputChannels;i++)
5773 {
5774 /* Only read as many channels as the user wants */
5775 fnSetInputChannel[wrapCntr](&pInfo->stream->bufferProcessor,
5776 i,
5777 ((unsigned char*)(data[wrapCntr]))+(i*pInfo->stream->capture.bytesPerSample),
5778 pInfo->stream->deviceInputChannels);
5779 }
5780 }
5781 }
5782 else
5783 {
5784 /* We haven't consumed anything from the ring buffer... */
5785 inputFramesAvailable = 0;
5786 /* If we have full-duplex, this is at startup, so mark no-input! */
5787 if (pInfo->stream->userOutputChannels>0 && pInfo->stream->userInputChannels>0)
5788 {
5789 PA_HP_TRACE((pInfo->stream->hLog, "Input startup, marking no input."));
5790 PaUtil_SetNoInput(&pInfo->stream->bufferProcessor);
5791 }
5792 }
5793
5794 if (processFullDuplex) /* full duplex */
5795 {
5796 /* Only call the EndBufferProcessing function when the total input frames == total output frames */
5797 const unsigned long totalInputFrameCount = pInfo->stream->bufferProcessor.hostInputFrameCount[0] + pInfo->stream->bufferProcessor.hostInputFrameCount[1];
5798 const unsigned long totalOutputFrameCount = pInfo->stream->bufferProcessor.hostOutputFrameCount[0] + pInfo->stream->bufferProcessor.hostOutputFrameCount[1];
5799
5800 if(totalInputFrameCount == totalOutputFrameCount && totalOutputFrameCount != 0)
5801 {
5802 framesProcessed = PaUtil_EndBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->cbResult);
5803 }
5804 else
5805 {
5806 framesProcessed = 0;
5807 }
5808 }
5809 else
5810 {
5811 framesProcessed = PaUtil_EndBufferProcessing(&pInfo->stream->bufferProcessor, &pInfo->cbResult);
5812 }
5813
5814 PA_HP_TRACE((pInfo->stream->hLog, "Frames processed: %u %s", framesProcessed, (pInfo->priming ? "(priming)":"")));
5815
5816 if( doChannelCopy )
5817 {
5818 DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;
5819 /* Copy the first output channel to the other channels */
5820 switch (pInfo->stream->render.bytesPerSample)
5821 {
5822 case 2:
5823 DuplicateFirstChannelInt16(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);
5824 break;
5825 case 3:
5826 DuplicateFirstChannelInt24(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);
5827 break;
5828 case 4:
5829 DuplicateFirstChannelInt32(packet->Header.Data, pInfo->stream->deviceOutputChannels, pInfo->stream->render.framesPerBuffer);
5830 break;
5831 default:
5832 assert(0); /* Unsupported format! */
5833 break;
5834 }
5835 }
5836 PaUtil_EndCpuLoadMeasurement( &pInfo->stream->cpuLoadMeasurer, framesProcessed );
5837
5838 if (inputFramesAvailable)
5839 {
5840 PaUtil_AdvanceRingBufferReadIndex(&pInfo->stream->ringBuffer, inputFramesAvailable);
5841 }
5842
5843 if (pInfo->renderTail != pInfo->renderHead)
5844 {
5845 if (!pInfo->stream->streamStop)
5846 {
5847 result = pInfo->stream->render.pPin->fnSubmitHandler(pInfo, pInfo->renderTail);
5848 if (result != paNoError)
5849 {
5850 PA_HP_TRACE((pInfo->stream->hLog, "Capture submit handler failed with result %d", result));
5851 return result;
5852 }
5853 }
5854 pInfo->renderTail++;
5855 if (!pInfo->pinsStarted && pInfo->priming == 0)
5856 {
5857 /* We start the pins here to allow "prime time" */
5858 if ((result = StartPins(pInfo)) == paNoError)
5859 {
5860 PA_HP_TRACE((pInfo->stream->hLog, "Starting pins!"));
5861 pInfo->pinsStarted = 1;
5862 }
5863 }
5864 }
5865 }
5866
5867 return result;
5868 }
5869
5870 static VOID CALLBACK TimerAPCWaveRTPolledMode(
5871 LPVOID lpArgToCompletionRoutine,
5872 DWORD dwTimerLowValue,
5873 DWORD dwTimerHighValue)
5874 {
5875 HANDLE* pHandles = (HANDLE*)lpArgToCompletionRoutine;
5876 if (pHandles[0]) SetEvent(pHandles[0]);
5877 if (pHandles[1]) SetEvent(pHandles[1]);
5878 }
5879
5880 static DWORD GetCurrentTimeInMillisecs()
5881 {
5882 return timeGetTime();
5883 }
5884
5885 PA_THREAD_FUNC ProcessingThread(void* pParam)
5886 {
5887 PaError result = paNoError;
5888 HANDLE hAVRT = NULL;
5889 HANDLE hTimer = NULL;
5890 HANDLE *handleArray = NULL;
5891 HANDLE timerEventHandles[2] = {0};
5892 unsigned noOfHandles = 0;
5893 unsigned captureEvents = 0;
5894 unsigned renderEvents = 0;
5895 unsigned timerPeriod = 0;
5896 DWORD timeStamp[2] = {0};
5897
5898 PaProcessThreadInfo info;
5899 memset(&info, 0, sizeof(PaProcessThreadInfo));
5900 info.stream = (PaWinWdmStream*)pParam;
5901
5902 info.stream->threadResult = paNoError;
5903
5904 PA_LOGE_;
5905
5906 info.ti.inputBufferAdcTime = 0.0;
5907 info.ti.currentTime = 0.0;
5908 info.ti.outputBufferDacTime = 0.0;
5909
5910 PA_DEBUG(("In buffer len: %.3f ms\n",(2000*info.stream->capture.framesPerBuffer) / info.stream->streamRepresentation.streamInfo.sampleRate));
5911 PA_DEBUG(("Out buffer len: %.3f ms\n",(2000*info.stream->render.framesPerBuffer) / info.stream->streamRepresentation.streamInfo.sampleRate));
5912 info.timeout = (DWORD)max(
5913 (2000*info.stream->render.framesPerBuffer/info.stream->streamRepresentation.streamInfo.sampleRate + 0.5),
5914 (2000*info.stream->capture.framesPerBuffer/info.stream->streamRepresentation.streamInfo.sampleRate + 0.5));
5915 info.timeout = max(info.timeout*8, 100);
5916 timerPeriod = info.timeout;
5917 PA_DEBUG(("Timeout = %ld ms\n",info.timeout));
5918
5919 /* Allocate handle array */
5920 handleArray = (HANDLE*)PaUtil_AllocateMemory((info.stream->capture.noOfPackets + info.stream->render.noOfPackets + 1) * sizeof(HANDLE));
5921
5922 /* Setup handle array for WFMO */
5923 if (info.stream->capture.pPin != 0)
5924 {
5925 handleArray[noOfHandles++] = info.stream->capture.events[0];
5926 if (info.stream->capture.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
5927 {
5928 unsigned i;
5929 for(i=1; i < info.stream->capture.noOfPackets; ++i)
5930 {
5931 handleArray[noOfHandles++] = info.stream->capture.events[i];
5932 }
5933 }
5934 captureEvents = noOfHandles;
5935 renderEvents = noOfHandles;
5936 }
5937
5938 if (info.stream->render.pPin != 0)
5939 {
5940 handleArray[noOfHandles++] = info.stream->render.events[0];
5941 if (info.stream->render.pPin->parentFilter->devInfo.streamingType == Type_kWaveCyclic)
5942 {
5943 unsigned i;
5944 for(i=1; i < info.stream->render.noOfPackets; ++i)
5945 {
5946 handleArray[noOfHandles++] = info.stream->render.events[i];
5947 }
5948 }
5949 renderEvents = noOfHandles;
5950 }
5951 handleArray[noOfHandles++] = info.stream->eventAbort;
5952 assert(noOfHandles <= (info.stream->capture.noOfPackets + info.stream->render.noOfPackets + 1));
5953
5954 /* Prepare render and capture pins */
5955 if ((result = PreparePinsForStart(&info)) != paNoError)
5956 {
5957 PA_DEBUG(("Failed to prepare device(s)!\n"));
5958 goto error;
5959 }
5960
5961 /* Init high speed logger */
5962 if (PaUtil_InitializeHighSpeedLog(&info.stream->hLog, 1000000) != paNoError)
5963 {
5964 PA_DEBUG(("Failed to init high speed logger!\n"));
5965 goto error;
5966 }
5967
5968 /* Heighten priority here */
5969 hAVRT = BumpThreadPriority();
5970
5971 /* If input only, we start the pins immediately */
5972 if (info.stream->render.pPin == 0)
5973 {
5974 if ((result = StartPins(&info)) != paNoError)
5975 {
5976 PA_DEBUG(("Failed to start device(s)!\n"));
5977 goto error;
5978 }
5979 info.pinsStarted = 1;
5980 }
5981
5982 /* Handle WaveRT polled mode */
5983 {
5984 const unsigned fs = (unsigned)info.stream->streamRepresentation.streamInfo.sampleRate;
5985 if (info.stream->capture.pPin != 0 && info.stream->capture.pPin->pinKsSubType == SubType_kPolled)
5986 {
5987 timerEventHandles[0] = info.stream->capture.events[0];
5988 timerPeriod = min(timerPeriod, (1000*info.stream->capture.framesPerBuffer)/fs);
5989 }
5990
5991 if (info.stream->render.pPin != 0 && info.stream->render.pPin->pinKsSubType == SubType_kPolled)
5992 {
5993 timerEventHandles[1] = info.stream->render.events[0];
5994 timerPeriod = min(timerPeriod, (1000*info.stream->render.framesPerBuffer)/fs);
5995 }
5996
5997 if (timerEventHandles[0] || timerEventHandles[1])
5998 {
5999 LARGE_INTEGER dueTime = {0};
6000
6001 timerPeriod=max(timerPeriod/5,1);
6002 PA_DEBUG(("Timer event handles=0x%04X,0x%04X period=%u ms", timerEventHandles[0], timerEventHandles[1], timerPeriod));
6003 hTimer = CreateWaitableTimer(0, FALSE, NULL);
6004 if (hTimer == NULL)
6005 {
6006 result = paUnanticipatedHostError;
6007 goto error;
6008 }
6009 /* invoke first timeout immediately */
6010 if (!SetWaitableTimer(hTimer, &dueTime, timerPeriod, TimerAPCWaveRTPolledMode, timerEventHandles, FALSE))
6011 {
6012 result = paUnanticipatedHostError;
6013 goto error;
6014 }
6015 PA_DEBUG(("Waitable timer started, period = %u ms\n", timerPeriod));
6016 }
6017 }
6018
6019 /* Mark stream as active */
6020 info.stream->streamActive = 1;
6021 info.stream->threadResult = paNoError;
6022
6023 /* Up and running... */
6024 SetEvent(info.stream->eventStreamStart[StreamStart_kOk]);
6025
6026 /* Take timestamp here */
6027 timeStamp[0] = timeStamp[1] = GetCurrentTimeInMillisecs();
6028
6029 while(!info.stream->streamAbort)
6030 {
6031 unsigned doProcessing = 1;
6032 unsigned wait = WaitForMultipleObjects(noOfHandles, handleArray, FALSE, 0);
6033 unsigned eventSignalled = wait - WAIT_OBJECT_0;
6034 DWORD dwCurrentTime = 0;
6035
6036 if (wait == WAIT_FAILED)
6037 {
6038 PA_DEBUG(("Wait failed = %ld! \n",wait));
6039 break;
6040 }
6041 if (wait == WAIT_TIMEOUT)
6042 {
6043 wait = WaitForMultipleObjectsEx(noOfHandles, handleArray, FALSE, 50, TRUE);
6044 eventSignalled = wait - WAIT_OBJECT_0;
6045 }
6046 else
6047 {
6048 if (eventSignalled < captureEvents)
6049 {
6050 if (PaUtil_GetRingBufferWriteAvailable(&info.stream->ringBuffer) == 0)
6051 {
6052 PA_HP_TRACE((info.stream->hLog, "!!!!! Input overflow !!!!!"));
6053 info.underover |= paInputOverflow;
6054 }
6055 }
6056 else if (eventSignalled < renderEvents)
6057 {
6058 if (!info.priming && info.renderHead - info.renderTail > 1)
6059 {
6060 PA_HP_TRACE((info.stream->hLog, "!!!!! Output underflow !!!!!"));
6061 info.underover |= paOutputUnderflow;
6062 }
6063 }
6064 }
6065
6066 /* Get event time */
6067 dwCurrentTime = GetCurrentTimeInMillisecs();
6068
6069 /* Since we can mix capture/render devices between WaveCyclic, WaveRT polled and WaveRT notification (3x3 combinations),
6070 we can't rely on the timeout of WFMO to check for device timeouts, we need to keep tally. */
6071 if (info.stream->capture.pPin && (dwCurrentTime - timeStamp[0]) >= info.timeout)
6072 {
6073 PA_DEBUG(("Timeout for capture device (%u ms)!", info.timeout, (dwCurrentTime - timeStamp[0])));
6074 result = paTimedOut;
6075 break;
6076 }
6077 if (info.stream->render.pPin && (dwCurrentTime - timeStamp[1]) >= info.timeout)
6078 {
6079 PA_DEBUG(("Timeout for render device (%u ms)!", info.timeout, (dwCurrentTime - timeStamp[1])));
6080 result = paTimedOut;
6081 break;
6082 }
6083
6084 if (wait == WAIT_IO_COMPLETION)
6085 {
6086 /* Waitable timer has fired! */
6087 PA_HP_TRACE((info.stream->hLog, "WAIT_IO_COMPLETION"));
6088 continue;
6089 }
6090
6091 if (wait == WAIT_TIMEOUT)
6092 {
6093 continue;
6094 }
6095 else
6096 {
6097 if (eventSignalled < captureEvents)
6098 {
6099 if (info.stream->capture.pPin->fnEventHandler(&info, eventSignalled) == paNoError)
6100 {
6101 timeStamp[0] = dwCurrentTime;
6102
6103 /* Since we use the ring buffer, we can submit the buffers directly */
6104 if (!info.stream->streamStop)
6105 {
6106 result = info.stream->capture.pPin->fnSubmitHandler(&info, info.captureTail);
6107 if (result != paNoError)
6108 {
6109 PA_HP_TRACE((info.stream->hLog, "Capture submit handler failed with result %d", result));
6110 break;
6111 }
6112 }
6113 ++info.captureTail;
6114 /* If full-duplex, let _only_ render event trigger processing. We still need the stream stop
6115 handling working, so let that be processed anyways... */
6116 if (info.stream->userOutputChannels > 0)
6117 {
6118 doProcessing = 0;
6119 }
6120 }
6121 }
6122 else if (eventSignalled < renderEvents)
6123 {
6124 timeStamp[1] = dwCurrentTime;
6125 eventSignalled -= captureEvents;
6126 info.stream->render.pPin->fnEventHandler(&info, eventSignalled);
6127 }
6128 else
6129 {
6130 assert(info.stream->streamAbort);
6131 PA_HP_TRACE((info.stream->hLog, "Stream abort!"));
6132 continue;
6133 }
6134 }
6135
6136 /* Handle processing */
6137 if (doProcessing)
6138 {
6139 result = PaDoProcessing(&info);
6140 if (result != paNoError)
6141 {
6142 PA_HP_TRACE((info.stream->hLog, "PaDoProcessing failed!"));
6143 break;
6144 }
6145 }
6146
6147 if(info.stream->streamStop && info.cbResult != paComplete)
6148 {
6149 PA_HP_TRACE((info.stream->hLog, "Stream stop! pending=%d",info.pending));
6150 info.cbResult = paComplete; /* Stop, but play remaining buffers */
6151 }
6152
6153 if(info.pending<=0)
6154 {
6155 PA_HP_TRACE((info.stream->hLog, "pending==0 finished..."));
6156 break;
6157 }
6158 if((!info.stream->render.pPin)&&(info.cbResult!=paContinue))
6159 {
6160 PA_HP_TRACE((info.stream->hLog, "record only cbResult=%d...",info.cbResult));
6161 break;
6162 }
6163 }
6164
6165 PA_DEBUG(("Finished processing loop\n"));
6166
6167 info.stream->threadResult = result;
6168 goto bailout;
6169
6170 error:
6171 PA_DEBUG(("Error starting processing thread\n"));
6172 /* Set the "error" event together with result */
6173 info.stream->threadResult = result;
6174 SetEvent(info.stream->eventStreamStart[StreamStart_kFailed]);
6175
6176 bailout:
6177 if (hTimer)
6178 {
6179 PA_DEBUG(("Waitable timer stopped\n", timerPeriod));
6180 CancelWaitableTimer(hTimer);
6181 CloseHandle(hTimer);
6182 hTimer = 0;
6183 }
6184
6185 if (info.pinsStarted)
6186 {
6187 StopPins(&info);
6188 }
6189
6190 /* Lower prio here */
6191 DropThreadPriority(hAVRT);
6192
6193 if (handleArray != NULL)
6194 {
6195 PaUtil_FreeMemory(handleArray);
6196 }
6197
6198 #if PA_TRACE_REALTIME_EVENTS
6199 if (info.stream->hLog)
6200 {
6201 PA_DEBUG(("Dumping highspeed trace...\n"));
6202 PaUtil_DumpHighSpeedLog(info.stream->hLog, "hp_trace.log");
6203 PaUtil_DiscardHighSpeedLog(info.stream->hLog);
6204 info.stream->hLog = 0;
6205 }
6206 #endif
6207 info.stream->streamActive = 0;
6208
6209 if((!info.stream->streamStop)&&(!info.stream->streamAbort))
6210 {
6211 /* Invoke the user stream finished callback */
6212 /* Only do it from here if not being stopped/aborted by user */
6213 if( info.stream->streamRepresentation.streamFinishedCallback != 0 )
6214 info.stream->streamRepresentation.streamFinishedCallback( info.stream->streamRepresentation.userData );
6215 }
6216 info.stream->streamStop = 0;
6217 info.stream->streamAbort = 0;
6218
6219 PA_LOGL_;
6220 return 0;
6221 }
6222
6223
6224 static PaError StartStream( PaStream *s )
6225 {
6226 PaError result = paNoError;
6227 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6228
6229 PA_LOGE_;
6230
6231 if (stream->streamThread != NULL)
6232 {
6233 return paStreamIsNotStopped;
6234 }
6235
6236 stream->streamStop = 0;
6237 stream->streamAbort = 0;
6238
6239 ResetStreamEvents(stream);
6240
6241 PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
6242
6243 stream->oldProcessPriority = GetPriorityClass(GetCurrentProcess());
6244 /* Uncomment the following line to enable dynamic boosting of the process
6245 * priority to real time for best low latency support
6246 * Disabled by default because RT processes can easily block the OS */
6247 /*ret = SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS);
6248 PA_DEBUG(("Class ret = %d;",ret));*/
6249
6250 stream->streamThread = CREATE_THREAD_FUNCTION (NULL, 0, ProcessingThread, stream, CREATE_SUSPENDED, NULL);
6251 if(stream->streamThread == NULL)
6252 {
6253 result = paInsufficientMemory;
6254 goto end;
6255 }
6256 ResumeThread(stream->streamThread);
6257
6258 switch (WaitForMultipleObjects(2, stream->eventStreamStart, FALSE, 5000))
6259 {
6260 case WAIT_OBJECT_0 + StreamStart_kOk:
6261 PA_DEBUG(("Processing thread started!\n"));
6262 result = paNoError;
6263 /* streamActive is set in processing thread */
6264 stream->streamStarted = 1;
6265 break;
6266 case WAIT_OBJECT_0 + StreamStart_kFailed:
6267 PA_DEBUG(("Processing thread start failed! (result=%d)\n", stream->threadResult));
6268 result = stream->threadResult;
6269 /* Wait for the stream to really exit */
6270 WaitForSingleObject(stream->streamThread, 200);
6271 CloseHandle(stream->streamThread);
6272 stream->streamThread = 0;
6273 break;
6274 case WAIT_TIMEOUT:
6275 default:
6276 result = paTimedOut;
6277 PaWinWDM_SetLastErrorInfo(result, "Failed to start processing thread (timeout)!");
6278 break;
6279 }
6280
6281 end:
6282 PA_LOGL_;
6283 return result;
6284 }
6285
6286
6287 static PaError StopStream( PaStream *s )
6288 {
6289 PaError result = paNoError;
6290 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6291 BOOL doCb = FALSE;
6292
6293 PA_LOGE_;
6294
6295 if(stream->streamActive)
6296 {
6297 DWORD dwExitCode;
6298 doCb = TRUE;
6299 stream->streamStop = 1;
6300 if (GetExitCodeThread(stream->streamThread, &dwExitCode) && dwExitCode == STILL_ACTIVE)
6301 {
6302 if (WaitForSingleObject(stream->streamThread, INFINITE) != WAIT_OBJECT_0)
6303 {
6304 PA_DEBUG(("StopStream: stream thread terminated\n"));
6305 TerminateThread(stream->streamThread, -1);
6306 result = paTimedOut;
6307 }
6308 }
6309 else
6310 {
6311 PA_DEBUG(("StopStream: GECT says not active, but streamActive is not false ??"));
6312 result = paUnanticipatedHostError;
6313 PaWinWDM_SetLastErrorInfo(result, "StopStream: GECT says not active, but streamActive = %d", stream->streamActive);
6314 }
6315 }
6316 else
6317 {
6318 if (stream->threadResult != paNoError)
6319 {
6320 PA_DEBUG(("StopStream: Stream not active (%d)\n", stream->threadResult));
6321 result = stream->threadResult;
6322 stream->threadResult = paNoError;
6323 }
6324 }
6325
6326 if (stream->streamThread != NULL)
6327 {
6328 CloseHandle(stream->streamThread);
6329 stream->streamThread = 0;
6330 }
6331 stream->streamStarted = 0;
6332 stream->streamActive = 0;
6333
6334 if(doCb)
6335 {
6336 /* Do user callback now after all state has been reset */
6337 /* This means it should be safe for the called function */
6338 /* to invoke e.g. StartStream */
6339 if( stream->streamRepresentation.streamFinishedCallback != 0 )
6340 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
6341 }
6342
6343 PA_LOGL_;
6344 return result;
6345 }
6346
6347 static PaError AbortStream( PaStream *s )
6348 {
6349 PaError result = paNoError;
6350 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6351 int doCb = 0;
6352
6353 PA_LOGE_;
6354
6355 if(stream->streamActive)
6356 {
6357 doCb = 1;
6358 stream->streamAbort = 1;
6359 SetEvent(stream->eventAbort); /* Signal immediately */
6360 if (WaitForSingleObject(stream->streamThread, 10000) != WAIT_OBJECT_0)
6361 {
6362 TerminateThread(stream->streamThread, -1);
6363 result = paTimedOut;
6364
6365 PA_DEBUG(("AbortStream: stream thread terminated\n"));
6366 }
6367 assert(!stream->streamActive);
6368 }
6369 CloseHandle(stream->streamThread);
6370 stream->streamThread = NULL;
6371 stream->streamStarted = 0;
6372
6373 if(doCb)
6374 {
6375 /* Do user callback now after all state has been reset */
6376 /* This means it should be safe for the called function */
6377 /* to invoke e.g. StartStream */
6378 if( stream->streamRepresentation.streamFinishedCallback != 0 )
6379 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
6380 }
6381
6382 stream->streamActive = 0;
6383 stream->streamStarted = 0;
6384
6385 PA_LOGL_;
6386 return result;
6387 }
6388
6389
6390 static PaError IsStreamStopped( PaStream *s )
6391 {
6392 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6393 int result = 0;
6394
6395 PA_LOGE_;
6396
6397 if(!stream->streamStarted)
6398 result = 1;
6399
6400 PA_LOGL_;
6401 return result;
6402 }
6403
6404
6405 static PaError IsStreamActive( PaStream *s )
6406 {
6407 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6408 int result = 0;
6409
6410 PA_LOGE_;
6411
6412 if(stream->streamActive)
6413 result = 1;
6414
6415 PA_LOGL_;
6416 return result;
6417 }
6418
6419
6420 static PaTime GetStreamTime( PaStream* s )
6421 {
6422 PA_LOGE_;
6423 PA_LOGL_;
6424 (void)s;
6425 return PaUtil_GetTime();
6426 }
6427
6428
6429 static double GetStreamCpuLoad( PaStream* s )
6430 {
6431 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6432 double result;
6433 PA_LOGE_;
6434 result = PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
6435 PA_LOGL_;
6436 return result;
6437 }
6438
6439
6440 /*
6441 As separate stream interfaces are used for blocking and callback
6442 streams, the following functions can be guaranteed to only be called
6443 for blocking streams.
6444 */
6445
6446 static PaError ReadStream( PaStream* s,
6447 void *buffer,
6448 unsigned long frames )
6449 {
6450 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6451
6452 PA_LOGE_;
6453
6454 /* suppress unused variable warnings */
6455 (void) buffer;
6456 (void) frames;
6457 (void) stream;
6458
6459 /* IMPLEMENT ME, see portaudio.h for required behavior*/
6460 PA_LOGL_;
6461 return paInternalError;
6462 }
6463
6464
6465 static PaError WriteStream( PaStream* s,
6466 const void *buffer,
6467 unsigned long frames )
6468 {
6469 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6470
6471 PA_LOGE_;
6472
6473 /* suppress unused variable warnings */
6474 (void) buffer;
6475 (void) frames;
6476 (void) stream;
6477
6478 /* IMPLEMENT ME, see portaudio.h for required behavior*/
6479 PA_LOGL_;
6480 return paInternalError;
6481 }
6482
6483
6484 static signed long GetStreamReadAvailable( PaStream* s )
6485 {
6486 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6487
6488 PA_LOGE_;
6489
6490 /* suppress unused variable warnings */
6491 (void) stream;
6492
6493 /* IMPLEMENT ME, see portaudio.h for required behavior*/
6494 PA_LOGL_;
6495 return 0;
6496 }
6497
6498
6499 static signed long GetStreamWriteAvailable( PaStream* s )
6500 {
6501 PaWinWdmStream *stream = (PaWinWdmStream*)s;
6502
6503 PA_LOGE_;
6504 /* suppress unused variable warnings */
6505 (void) stream;
6506
6507 /* IMPLEMENT ME, see portaudio.h for required behavior*/
6508 PA_LOGL_;
6509 return 0;
6510 }
6511
6512 /***************************************************************************************/
6513 /* Event and submit handlers for WaveCyclic */
6514 /***************************************************************************************/
6515
6516 static PaError PaPinCaptureEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6517 {
6518 PaError result = paNoError;
6519 ring_buffer_size_t frameCount;
6520 DATAPACKET* packet = pInfo->stream->capture.packets + eventIndex;
6521
6522 assert( eventIndex < pInfo->stream->capture.noOfPackets );
6523
6524 if (packet->Header.DataUsed == 0)
6525 {
6526 PA_HP_TRACE((pInfo->stream->hLog, ">>> Capture bogus event (no data): idx=%u", eventIndex));
6527
6528 /* 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
6529 on startup of streaming, where it erroneously sets the event without the corresponding buffer being filled (DataUsed == 0) */
6530 ResetEvent(packet->Signal.hEvent);
6531
6532 result = -1; /* Only need this to be NOT paNoError */
6533 }
6534 else
6535 {
6536 pInfo->capturePackets[pInfo->captureHead & cPacketsArrayMask].packet = packet;
6537
6538 frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer, packet->Header.Data, pInfo->stream->capture.framesPerBuffer);
6539
6540 PA_HP_TRACE((pInfo->stream->hLog, ">>> Capture event: idx=%u (frames=%u)", eventIndex, frameCount));
6541 ++pInfo->captureHead;
6542 }
6543
6544 --pInfo->pending; /* This needs to be done in either case */
6545 return result;
6546 }
6547
6548 static PaError PaPinCaptureSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6549 {
6550 PaError result = paNoError;
6551 DATAPACKET* packet = pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet;
6552 pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;
6553 assert(packet != 0);
6554 PA_HP_TRACE((pInfo->stream->hLog, "Capture submit: %u", eventIndex));
6555 packet->Header.DataUsed = 0; /* Reset for reuse */
6556 packet->Header.OptionsFlags = 0; /* Reset for reuse. Required for e.g. Focusrite Scarlett 2i4 (1st Gen) see #310 */
6557 ResetEvent(packet->Signal.hEvent);
6558 result = PinRead(pInfo->stream->capture.pPin->handle, packet);
6559 ++pInfo->pending;
6560 return result;
6561 }
6562
6563 static PaError PaPinRenderEventHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6564 {
6565 assert( eventIndex < pInfo->stream->render.noOfPackets );
6566
6567 pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask].packet = pInfo->stream->render.packets + eventIndex;
6568 PA_HP_TRACE((pInfo->stream->hLog, "<<< Render event : idx=%u head=%u", eventIndex, pInfo->renderHead));
6569 ++pInfo->renderHead;
6570 --pInfo->pending;
6571 return paNoError;
6572 }
6573
6574 static PaError PaPinRenderSubmitHandler_WaveCyclic(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6575 {
6576 PaError result = paNoError;
6577 DATAPACKET* packet = pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet;
6578 pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;
6579 assert(packet != 0);
6580
6581 PA_HP_TRACE((pInfo->stream->hLog, "Render submit : %u idx=%u", pInfo->renderTail, (unsigned)(packet - pInfo->stream->render.packets)));
6582 ResetEvent(packet->Signal.hEvent);
6583 result = PinWrite(pInfo->stream->render.pPin->handle, packet);
6584 /* Reset event, just in case we have an analogous situation to capture (see PaPinCaptureSubmitHandler_WaveCyclic) */
6585 ++pInfo->pending;
6586 if (pInfo->priming)
6587 {
6588 --pInfo->priming;
6589 }
6590 return result;
6591 }
6592
6593 /***************************************************************************************/
6594 /* Event and submit handlers for WaveRT */
6595 /***************************************************************************************/
6596
6597 static PaError PaPinCaptureEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6598 {
6599 unsigned long pos;
6600 unsigned realInBuf;
6601 unsigned frameCount;
6602 PaWinWdmIOInfo* pCapture = &pInfo->stream->capture;
6603 const unsigned halfInputBuffer = pCapture->hostBufferSize >> 1;
6604 PaWinWdmPin* pin = pCapture->pPin;
6605 DATAPACKET* packet = 0;
6606
6607 /* Get hold of current ADC position */
6608 pin->fnAudioPosition(pin, &pos);
6609 /* Wrap it (robi: why not use hw latency compensation here ?? because pos then gets _way_ off from
6610 where it should be, i.e. at beginning or half buffer position. Why? No idea.) */
6611
6612 pos %= pCapture->hostBufferSize;
6613 /* Then realInBuf will point to "other" half of double buffer */
6614 realInBuf = pos < halfInputBuffer ? 1U : 0U;
6615
6616 packet = pInfo->stream->capture.packets + realInBuf;
6617
6618 /* Call barrier (or dummy) */
6619 pin->fnMemBarrier();
6620
6621 /* Put it in queue */
6622 frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer, packet->Header.Data, pCapture->framesPerBuffer);
6623
6624 pInfo->capturePackets[pInfo->captureHead & cPacketsArrayMask].packet = packet;
6625
6626 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));
6627
6628 ++pInfo->captureHead;
6629 --pInfo->pending;
6630
6631 return paNoError;
6632 }
6633
6634 static PaError PaPinCaptureEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6635 {
6636 unsigned long pos;
6637 unsigned bytesToRead;
6638 PaWinWdmIOInfo* pCapture = &pInfo->stream->capture;
6639 const unsigned halfInputBuffer = pCapture->hostBufferSize>>1;
6640 PaWinWdmPin* pin = pInfo->stream->capture.pPin;
6641
6642 /* Get hold of current ADC position */
6643 pin->fnAudioPosition(pin, &pos);
6644 /* Wrap it (robi: why not use hw latency compensation here ?? because pos then gets _way_ off from
6645 where it should be, i.e. at beginning or half buffer position. Why? No idea.) */
6646 /* Compensate for HW FIFO to get to last read buffer position */
6647 pos += pin->hwLatency;
6648 pos %= pCapture->hostBufferSize;
6649 /* Need to align position on frame boundary */
6650 pos &= ~(pCapture->bytesPerFrame - 1);
6651
6652 /* Call barrier (or dummy) */
6653 pin->fnMemBarrier();
6654
6655 /* Put it in "queue" */
6656 bytesToRead = (pCapture->hostBufferSize + pos - pCapture->lastPosition) % pCapture->hostBufferSize;
6657 if (bytesToRead > 0)
6658 {
6659 unsigned frameCount = PaUtil_WriteRingBuffer(&pInfo->stream->ringBuffer,
6660 pCapture->hostBuffer + pCapture->lastPosition,
6661 bytesToRead / pCapture->bytesPerFrame);
6662
6663 pCapture->lastPosition = (pCapture->lastPosition + frameCount * pCapture->bytesPerFrame) % pCapture->hostBufferSize;
6664
6665 PA_HP_TRACE((pInfo->stream->hLog, "Capture event (WaveRTPolled): pos = %4.1lf%%, framesRead=%u", (pos * 100.0 / pCapture->hostBufferSize), frameCount));
6666 ++pInfo->captureHead;
6667 --pInfo->pending;
6668 }
6669 return paNoError;
6670 }
6671
6672 static PaError PaPinCaptureSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6673 {
6674 pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;
6675 ++pInfo->pending;
6676 return paNoError;
6677 }
6678
6679 static PaError PaPinCaptureSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6680 {
6681 pInfo->capturePackets[pInfo->captureTail & cPacketsArrayMask].packet = 0;
6682 ++pInfo->pending;
6683 return paNoError;
6684 }
6685
6686 static PaError PaPinRenderEventHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6687 {
6688 unsigned long pos;
6689 unsigned realOutBuf;
6690 PaWinWdmIOInfo* pRender = &pInfo->stream->render;
6691 const unsigned halfOutputBuffer = pRender->hostBufferSize >> 1;
6692 PaWinWdmPin* pin = pInfo->stream->render.pPin;
6693 PaIOPacket* ioPacket = &pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask];
6694
6695 /* Get hold of current DAC position */
6696 pin->fnAudioPosition(pin, &pos);
6697 /* Compensate for HW FIFO to get to last read buffer position */
6698 pos += pin->hwLatency;
6699 /* Wrap it */
6700 pos %= pRender->hostBufferSize;
6701 /* And align it, not sure its really needed though */
6702 pos &= ~(pRender->bytesPerFrame - 1);
6703 /* Then realOutBuf will point to "other" half of double buffer */
6704 realOutBuf = pos < halfOutputBuffer ? 1U : 0U;
6705
6706 if (pInfo->priming)
6707 {
6708 realOutBuf = pInfo->renderHead & 0x1;
6709 }
6710 ioPacket->packet = pInfo->stream->render.packets + realOutBuf;
6711 ioPacket->startByte = realOutBuf * halfOutputBuffer;
6712 ioPacket->lengthBytes = halfOutputBuffer;
6713
6714 PA_HP_TRACE((pInfo->stream->hLog, "Render event (WaveRT) : idx=%u head=%u (pos = %4.1lf%%)", realOutBuf, pInfo->renderHead, (pos * 100.0 / pRender->hostBufferSize) ));
6715
6716 ++pInfo->renderHead;
6717 --pInfo->pending;
6718 return paNoError;
6719 }
6720
6721 static PaError PaPinRenderEventHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6722 {
6723 unsigned long pos;
6724 unsigned realOutBuf;
6725 unsigned bytesToWrite;
6726
6727 PaWinWdmIOInfo* pRender = &pInfo->stream->render;
6728 const unsigned halfOutputBuffer = pRender->hostBufferSize >> 1;
6729 PaWinWdmPin* pin = pInfo->stream->render.pPin;
6730 PaIOPacket* ioPacket = &pInfo->renderPackets[pInfo->renderHead & cPacketsArrayMask];
6731
6732 /* Get hold of current DAC position */
6733 pin->fnAudioPosition(pin, &pos);
6734 /* Compensate for HW FIFO to get to last read buffer position */
6735 pos += pin->hwLatency;
6736 /* Wrap it */
6737 pos %= pRender->hostBufferSize;
6738 /* And align it, not sure its really needed though */
6739 pos &= ~(pRender->bytesPerFrame - 1);
6740
6741 if (pInfo->priming)
6742 {
6743 realOutBuf = pInfo->renderHead & 0x1;
6744 ioPacket->packet = pInfo->stream->render.packets + realOutBuf;
6745 ioPacket->startByte = realOutBuf * halfOutputBuffer;
6746 ioPacket->lengthBytes = halfOutputBuffer;
6747 ++pInfo->renderHead;
6748 --pInfo->pending;
6749 }
6750 else
6751 {
6752 bytesToWrite = (pRender->hostBufferSize + pos - pRender->lastPosition) % pRender->hostBufferSize;
6753 ++pRender->pollCntr;
6754 if (bytesToWrite >= halfOutputBuffer)
6755 {
6756 realOutBuf = (pos < halfOutputBuffer) ? 1U : 0U;
6757 ioPacket->packet = pInfo->stream->render.packets + realOutBuf;
6758 pRender->lastPosition = realOutBuf ? 0U : halfOutputBuffer;
6759 ioPacket->startByte = realOutBuf * halfOutputBuffer;
6760 ioPacket->lengthBytes = halfOutputBuffer;
6761 ++pInfo->renderHead;
6762 --pInfo->pending;
6763 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));
6764 pRender->pollCntr = 0;
6765 }
6766 }
6767 return paNoError;
6768 }
6769
6770 static PaError PaPinRenderSubmitHandler_WaveRTEvent(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6771 {
6772 PaWinWdmPin* pin = pInfo->stream->render.pPin;
6773 pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;
6774 /* Call barrier (if needed) */
6775 pin->fnMemBarrier();
6776 PA_HP_TRACE((pInfo->stream->hLog, "Render submit (WaveRT) : submit=%u", pInfo->renderTail));
6777 ++pInfo->pending;
6778 if (pInfo->priming)
6779 {
6780 --pInfo->priming;
6781 if (pInfo->priming)
6782 {
6783 PA_HP_TRACE((pInfo->stream->hLog, "Setting WaveRT event for priming (2)"));
6784 SetEvent(pInfo->stream->render.events[0]);
6785 }
6786 }
6787 return paNoError;
6788 }
6789
6790 static PaError PaPinRenderSubmitHandler_WaveRTPolled(PaProcessThreadInfo* pInfo, unsigned eventIndex)
6791 {
6792 PaWinWdmPin* pin = pInfo->stream->render.pPin;
6793 pInfo->renderPackets[pInfo->renderTail & cPacketsArrayMask].packet = 0;
6794 /* Call barrier (if needed) */
6795 pin->fnMemBarrier();
6796 PA_HP_TRACE((pInfo->stream->hLog, "Render submit (WaveRTPolled) : submit=%u", pInfo->renderTail));
6797 ++pInfo->pending;
6798 if (pInfo->priming)
6799 {
6800 --pInfo->priming;
6801 if (pInfo->priming)
6802 {
6803 PA_HP_TRACE((pInfo->stream->hLog, "Setting WaveRT event for priming (2)"));
6804 SetEvent(pInfo->stream->render.events[0]);
6805 }
6806 }
6807 return paNoError;
6808 }
6809 #endif