Debian Codegraph @

src/hostapi/wasapi/pa_win_wasapi.c

raw
1 /*
2 * Portable Audio I/O Library WASAPI implementation
3 * Copyright (c) 2006-2010 David Viens
4 * Copyright (c) 2010-2019 Dmitry Kostjuchenko
5 *
6 * Based on the Open Source API proposed by Ross Bencina
7 * Copyright (c) 1999-2019 Ross Bencina, Phil Burk
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining
10 * a copy of this software and associated documentation files
11 * (the "Software"), to deal in the Software without restriction,
12 * including without limitation the rights to use, copy, modify, merge,
13 * publish, distribute, sublicense, and/or sell copies of the Software,
14 * and to permit persons to whom the Software is furnished to do so,
15 * subject to the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
24 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
25 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 */
28
29 /*
30 * The text above constitutes the entire PortAudio license; however,
31 * the PortAudio community also makes the following non-binding requests:
32 *
33 * Any person wishing to distribute modifications to the Software is
34 * requested to send the modifications to the original developer so that
35 * they can be incorporated into the canonical version. It is also
36 * requested that these non-binding requests be included along with the
37 * license above.
38 */
39
40 /** @file
41 @ingroup hostapi_src
42 @brief WASAPI implementation of support for a host API.
43 @note pa_wasapi currently requires minimum VC 2005, and the latest Vista SDK
44 */
45
46 #include <windows.h>
47 #include <stdio.h>
48 #include <process.h>
49 #include <assert.h>
50
51 // Max device count (if defined) causes max constant device count in the device list that
52 // enables PaWasapi_UpdateDeviceList() API and makes it possible to update WASAPI list dynamically
53 #ifndef PA_WASAPI_MAX_CONST_DEVICE_COUNT
54 #define PA_WASAPI_MAX_CONST_DEVICE_COUNT 0 // Force basic behavior by defining 0 if not defined by user
55 #endif
56
57 // Fallback from Event to the Polling method in case if latency is higher than 21.33ms, as it allows to use
58 // 100% of CPU inside the PA's callback.
59 // Note: Some USB DAC drivers are buggy when Polling method is forced in Exclusive mode, audio output becomes
60 // unstable with a lot of interruptions, therefore this define is optional. The default behavior is to
61 // not change the Event mode to Polling and use the mode which user provided.
62 //#define PA_WASAPI_FORCE_POLL_IF_LARGE_BUFFER
63
64 //! Poll mode time slots logging.
65 //#define PA_WASAPI_LOG_TIME_SLOTS
66
67 // WinRT
68 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
69 #define PA_WINRT
70 #define INITGUID
71 #endif
72
73 // WASAPI
74 // using adjustments for MinGW build from @mgeier/MXE
75 // https://github.com/mxe/mxe/commit/f4bbc45682f021948bdaefd9fd476e2a04c4740f
76 #include <mmreg.h> // must be before other Wasapi headers
77 #if defined(_MSC_VER) && (_MSC_VER >= 1400) || defined(__MINGW64_VERSION_MAJOR)
78 #include <avrt.h>
79 #define COBJMACROS
80 #include <audioclient.h>
81 #include <endpointvolume.h>
82 #define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
83 #ifndef _MSC_VER
84 #include <functiondiscoverykeys_devpkey.h>
85 #endif
86 #include <functiondiscoverykeys.h>
87 #include <mmdeviceapi.h>
88 #include <devicetopology.h> // Used to get IKsJackDescription interface
89 #undef INITGUID
90 // Visual Studio 2010 does not support the inline keyword
91 #if (_MSC_VER <= 1600)
92 #define inline _inline
93 #endif
94 #endif
95 #ifndef __MWERKS__
96 #include <malloc.h>
97 #include <memory.h>
98 #endif
99 #ifndef PA_WINRT
100 #include <mmsystem.h>
101 #endif
102
103 #include "pa_util.h"
104 #include "pa_allocation.h"
105 #include "pa_hostapi.h"
106 #include "pa_stream.h"
107 #include "pa_cpuload.h"
108 #include "pa_process.h"
109 #include "pa_win_wasapi.h"
110 #include "pa_debugprint.h"
111 #include "pa_ringbuffer.h"
112 #include "pa_win_coinitialize.h"
113
114 #if !defined(NTDDI_VERSION) || (defined(__GNUC__) && (__GNUC__ <= 6) && !defined(__MINGW64__))
115
116 #undef WINVER
117 #undef _WIN32_WINNT
118 #define WINVER 0x0600 // VISTA
119 #define _WIN32_WINNT WINVER
120
121 #ifndef WINAPI
122 #define WINAPI __stdcall
123 #endif
124
125 #ifndef __unaligned
126 #define __unaligned
127 #endif
128
129 #ifndef __C89_NAMELESS
130 #define __C89_NAMELESS
131 #endif
132
133 #ifndef _AVRT_ //<< fix MinGW dummy compile by defining missing type: AVRT_PRIORITY
134 typedef enum _AVRT_PRIORITY
135 {
136 AVRT_PRIORITY_LOW = -1,
137 AVRT_PRIORITY_NORMAL,
138 AVRT_PRIORITY_HIGH,
139 AVRT_PRIORITY_CRITICAL
140 } AVRT_PRIORITY, *PAVRT_PRIORITY;
141 #endif
142
143 #include <basetyps.h> // << for IID/CLSID
144 #include <rpcsal.h>
145 #include <sal.h>
146
147 #ifndef __LPCGUID_DEFINED__
148 #define __LPCGUID_DEFINED__
149 typedef const GUID *LPCGUID;
150 #endif
151 typedef GUID IID;
152 typedef GUID CLSID;
153
154 #ifndef PROPERTYKEY_DEFINED
155 #define PROPERTYKEY_DEFINED
156 typedef struct _tagpropertykey
157 {
158 GUID fmtid;
159 DWORD pid;
160 } PROPERTYKEY;
161 #endif
162
163 #ifdef __midl_proxy
164 #define __MIDL_CONST
165 #else
166 #define __MIDL_CONST const
167 #endif
168
169 #ifdef WIN64
170 #include <wtypes.h>
171 #define FASTCALL
172 #include <oleidl.h>
173 #include <objidl.h>
174 #else
175 typedef struct _BYTE_BLOB
176 {
177 unsigned long clSize;
178 unsigned char abData[ 1 ];
179 } BYTE_BLOB;
180 typedef /* [unique] */ __RPC_unique_pointer BYTE_BLOB *UP_BYTE_BLOB;
181 typedef LONGLONG REFERENCE_TIME;
182 #define NONAMELESSUNION
183 #endif
184
185 #ifndef NT_SUCCESS
186 typedef LONG NTSTATUS;
187 #endif
188
189 #ifndef WAVE_FORMAT_IEEE_FLOAT
190 #define WAVE_FORMAT_IEEE_FLOAT 0x0003 // 32-bit floating-point
191 #endif
192
193 #ifndef __MINGW_EXTENSION
194 #if defined(__GNUC__) || defined(__GNUG__)
195 #define __MINGW_EXTENSION __extension__
196 #else
197 #define __MINGW_EXTENSION
198 #endif
199 #endif
200
201 #include <sdkddkver.h>
202 #include <propkeydef.h>
203 #define COBJMACROS
204 #define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
205 #include <audioclient.h>
206 #include <mmdeviceapi.h>
207 #include <endpointvolume.h>
208 #include <functiondiscoverykeys.h>
209 #include <devicetopology.h> // Used to get IKsJackDescription interface
210 #undef INITGUID
211
212 #endif // NTDDI_VERSION
213
214 // Missing declarations for WinRT
215 #ifdef PA_WINRT
216
217 #define DEVICE_STATE_ACTIVE 0x00000001
218
219 typedef enum _EDataFlow
220 {
221 eRender = 0,
222 eCapture = ( eRender + 1 ) ,
223 eAll = ( eCapture + 1 ) ,
224 EDataFlow_enum_count = ( eAll + 1 )
225 }
226 EDataFlow;
227
228 typedef enum _EndpointFormFactor
229 {
230 RemoteNetworkDevice = 0,
231 Speakers = ( RemoteNetworkDevice + 1 ) ,
232 LineLevel = ( Speakers + 1 ) ,
233 Headphones = ( LineLevel + 1 ) ,
234 Microphone = ( Headphones + 1 ) ,
235 Headset = ( Microphone + 1 ) ,
236 Handset = ( Headset + 1 ) ,
237 UnknownDigitalPassthrough = ( Handset + 1 ) ,
238 SPDIF = ( UnknownDigitalPassthrough + 1 ) ,
239 HDMI = ( SPDIF + 1 ) ,
240 UnknownFormFactor = ( HDMI + 1 )
241 }
242 EndpointFormFactor;
243
244 #endif
245
246 #ifndef GUID_SECT
247 #define GUID_SECT
248 #endif
249
250 #define __DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
251 #define __DEFINE_IID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const IID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
252 #define __DEFINE_CLSID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const CLSID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
253 #define PA_DEFINE_CLSID(className, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
254 __DEFINE_CLSID(pa_CLSID_##className, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
255 #define PA_DEFINE_IID(interfaceName, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
256 __DEFINE_IID(pa_IID_##interfaceName, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
257
258 // "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"
259 PA_DEFINE_IID(IAudioClient, 1cb9ad4c, dbfa, 4c32, b1, 78, c2, f5, 68, a7, 03, b2);
260 // "726778CD-F60A-4EDA-82DE-E47610CD78AA"
261 PA_DEFINE_IID(IAudioClient2, 726778cd, f60a, 4eda, 82, de, e4, 76, 10, cd, 78, aa);
262 // "7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42"
263 PA_DEFINE_IID(IAudioClient3, 7ed4ee07, 8e67, 4cd4, 8c, 1a, 2b, 7a, 59, 87, ad, 42);
264 // "1BE09788-6894-4089-8586-9A2A6C265AC5"
265 PA_DEFINE_IID(IMMEndpoint, 1be09788, 6894, 4089, 85, 86, 9a, 2a, 6c, 26, 5a, c5);
266 // "A95664D2-9614-4F35-A746-DE8DB63617E6"
267 PA_DEFINE_IID(IMMDeviceEnumerator, a95664d2, 9614, 4f35, a7, 46, de, 8d, b6, 36, 17, e6);
268 // "BCDE0395-E52F-467C-8E3D-C4579291692E"
269 PA_DEFINE_CLSID(IMMDeviceEnumerator,bcde0395, e52f, 467c, 8e, 3d, c4, 57, 92, 91, 69, 2e);
270 // "F294ACFC-3146-4483-A7BF-ADDCA7C260E2"
271 PA_DEFINE_IID(IAudioRenderClient, f294acfc, 3146, 4483, a7, bf, ad, dc, a7, c2, 60, e2);
272 // "C8ADBD64-E71E-48a0-A4DE-185C395CD317"
273 PA_DEFINE_IID(IAudioCaptureClient, c8adbd64, e71e, 48a0, a4, de, 18, 5c, 39, 5c, d3, 17);
274 // *2A07407E-6497-4A18-9787-32F79BD0D98F* Or this??
275 PA_DEFINE_IID(IDeviceTopology, 2A07407E, 6497, 4A18, 97, 87, 32, f7, 9b, d0, d9, 8f);
276 // *AE2DE0E4-5BCA-4F2D-AA46-5D13F8FDB3A9*
277 PA_DEFINE_IID(IPart, AE2DE0E4, 5BCA, 4F2D, aa, 46, 5d, 13, f8, fd, b3, a9);
278 // *4509F757-2D46-4637-8E62-CE7DB944F57B*
279 PA_DEFINE_IID(IKsJackDescription, 4509F757, 2D46, 4637, 8e, 62, ce, 7d, b9, 44, f5, 7b);
280
281 // Media formats:
282 __DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
283 __DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_ADPCM, 0x00000002, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
284 __DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
285
286 #ifdef __IAudioClient2_INTERFACE_DEFINED__
287 typedef enum _pa_AUDCLNT_STREAMOPTIONS {
288 pa_AUDCLNT_STREAMOPTIONS_NONE = 0x00,
289 pa_AUDCLNT_STREAMOPTIONS_RAW = 0x01,
290 pa_AUDCLNT_STREAMOPTIONS_MATCH_FORMAT = 0x02
291 } pa_AUDCLNT_STREAMOPTIONS;
292 typedef struct _pa_AudioClientProperties {
293 UINT32 cbSize;
294 BOOL bIsOffload;
295 AUDIO_STREAM_CATEGORY eCategory;
296 pa_AUDCLNT_STREAMOPTIONS Options;
297 } pa_AudioClientProperties;
298 #define PA_AUDIOCLIENTPROPERTIES_SIZE_CATEGORY (sizeof(pa_AudioClientProperties) - sizeof(pa_AUDCLNT_STREAMOPTIONS))
299 #define PA_AUDIOCLIENTPROPERTIES_SIZE_OPTIONS sizeof(pa_AudioClientProperties)
300 #endif // __IAudioClient2_INTERFACE_DEFINED__
301
302 /* use CreateThread for CYGWIN/Windows Mobile, _beginthreadex for all others */
303 #if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
304 #define CREATE_THREAD(PROC) (HANDLE)_beginthreadex( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
305 #define PA_THREAD_FUNC static unsigned WINAPI
306 #define PA_THREAD_ID unsigned
307 #else
308 #define CREATE_THREAD(PROC) CreateThread( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
309 #define PA_THREAD_FUNC static DWORD WINAPI
310 #define PA_THREAD_ID DWORD
311 #endif
312
313 // Thread function forward decl.
314 PA_THREAD_FUNC ProcThreadEvent(void *param);
315 PA_THREAD_FUNC ProcThreadPoll(void *param);
316
317 // Error codes (available since Windows 7)
318 #ifndef AUDCLNT_E_BUFFER_ERROR
319 #define AUDCLNT_E_BUFFER_ERROR AUDCLNT_ERR(0x018)
320 #endif
321 #ifndef AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
322 #define AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED AUDCLNT_ERR(0x019)
323 #endif
324 #ifndef AUDCLNT_E_INVALID_DEVICE_PERIOD
325 #define AUDCLNT_E_INVALID_DEVICE_PERIOD AUDCLNT_ERR(0x020)
326 #endif
327
328 // Stream flags (available since Windows 7)
329 #ifndef AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
330 #define AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
331 #endif
332 #ifndef AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
333 #define AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
334 #endif
335
336 #define PA_WASAPI_DEVICE_ID_LEN 256
337 #define PA_WASAPI_DEVICE_NAME_LEN 128
338 #ifdef PA_WINRT
339 #define PA_WASAPI_DEVICE_MAX_COUNT 16
340 #endif
341
342 enum { S_INPUT = 0, S_OUTPUT = 1, S_COUNT = 2, S_FULLDUPLEX = 0 };
343
344 // Number of packets which compose single contignous buffer. With trial and error it was calculated
345 // that WASAPI Input sub-system uses 6 packets per whole buffer. Please provide more information
346 // or corrections if available.
347 enum { WASAPI_PACKETS_PER_INPUT_BUFFER = 6 };
348
349 #define STATIC_ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
350
351 #define PRINT(x) PA_DEBUG(x);
352
353 #define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \
354 PaUtil_SetLastHostErrorInfo( paWASAPI, errorCode, errorText )
355
356 #define PA_WASAPI__IS_FULLDUPLEX(STREAM) ((STREAM)->in.clientProc && (STREAM)->out.clientProc)
357
358 #ifndef IF_FAILED_JUMP
359 #define IF_FAILED_JUMP(hr, label) if(FAILED(hr)) goto label;
360 #endif
361
362 #ifndef IF_FAILED_INTERNAL_ERROR_JUMP
363 #define IF_FAILED_INTERNAL_ERROR_JUMP(hr, error, label) if(FAILED(hr)) { error = paInternalError; goto label; }
364 #endif
365
366 #define SAFE_CLOSE(h) if ((h) != NULL) { CloseHandle((h)); (h) = NULL; }
367 #define SAFE_RELEASE(punk) if ((punk) != NULL) { (punk)->lpVtbl->Release((punk)); (punk) = NULL; }
368
369 // Mixer function
370 typedef void (*MixMonoToStereoF) (void *__to, const void *__from, UINT32 count);
371
372 // AVRT is the new "multimedia scheduling stuff"
373 #ifndef PA_WINRT
374 typedef BOOL (WINAPI *FAvRtCreateThreadOrderingGroup) (PHANDLE,PLARGE_INTEGER,GUID*,PLARGE_INTEGER);
375 typedef BOOL (WINAPI *FAvRtDeleteThreadOrderingGroup) (HANDLE);
376 typedef BOOL (WINAPI *FAvRtWaitOnThreadOrderingGroup) (HANDLE);
377 typedef HANDLE (WINAPI *FAvSetMmThreadCharacteristics) (LPCSTR,LPDWORD);
378 typedef BOOL (WINAPI *FAvRevertMmThreadCharacteristics)(HANDLE);
379 typedef BOOL (WINAPI *FAvSetMmThreadPriority) (HANDLE,AVRT_PRIORITY);
380 static HMODULE hDInputDLL = 0;
381 FAvRtCreateThreadOrderingGroup pAvRtCreateThreadOrderingGroup = NULL;
382 FAvRtDeleteThreadOrderingGroup pAvRtDeleteThreadOrderingGroup = NULL;
383 FAvRtWaitOnThreadOrderingGroup pAvRtWaitOnThreadOrderingGroup = NULL;
384 FAvSetMmThreadCharacteristics pAvSetMmThreadCharacteristics = NULL;
385 FAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
386 FAvSetMmThreadPriority pAvSetMmThreadPriority = NULL;
387 #endif
388
389 #define _GetProc(fun, type, name) { \
390 fun = (type) GetProcAddress(hDInputDLL,name); \
391 if (fun == NULL) { \
392 PRINT(("GetProcAddr failed for %s" ,name)); \
393 return FALSE; \
394 } \
395 } \
396
397 // ------------------------------------------------------------------------------------------
398 /* prototypes for functions declared in this file */
399 #ifdef __cplusplus
400 extern "C"
401 {
402 #endif /* __cplusplus */
403 PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
404 #ifdef __cplusplus
405 }
406 #endif /* __cplusplus */
407 // dummy entry point for other compilers and sdks
408 // currently built using RC1 SDK (5600)
409 //#if _MSC_VER < 1400
410 //PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
411 //{
412 //return paNoError;
413 //}
414 //#else
415
416 // ------------------------------------------------------------------------------------------
417 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
418 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
419 const PaStreamParameters *inputParameters,
420 const PaStreamParameters *outputParameters,
421 double sampleRate );
422 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
423 PaStream** s,
424 const PaStreamParameters *inputParameters,
425 const PaStreamParameters *outputParameters,
426 double sampleRate,
427 unsigned long framesPerBuffer,
428 PaStreamFlags streamFlags,
429 PaStreamCallback *streamCallback,
430 void *userData );
431 static PaError CloseStream( PaStream* stream );
432 static PaError StartStream( PaStream *stream );
433 static PaError StopStream( PaStream *stream );
434 static PaError AbortStream( PaStream *stream );
435 static PaError IsStreamStopped( PaStream *s );
436 static PaError IsStreamActive( PaStream *stream );
437 static PaTime GetStreamTime( PaStream *stream );
438 static double GetStreamCpuLoad( PaStream* stream );
439 static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
440 static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
441 static signed long GetStreamReadAvailable( PaStream* stream );
442 static signed long GetStreamWriteAvailable( PaStream* stream );
443
444 // ------------------------------------------------------------------------------------------
445 /*
446 These are fields that can be gathered from IDevice and IAudioDevice PRIOR to Initialize, and
447 done in first pass i assume that neither of these will cause the Driver to "load", but again,
448 who knows how they implement their stuff
449 */
450 typedef struct PaWasapiDeviceInfo
451 {
452 // Device
453 #ifndef PA_WINRT
454 IMMDevice *device;
455 #endif
456
457 // device Id
458 WCHAR deviceId[PA_WASAPI_DEVICE_ID_LEN];
459
460 // from GetState
461 DWORD state;
462
463 // Fields filled from IAudioDevice (_prior_ to Initialize)
464 // from GetDevicePeriod(
465 REFERENCE_TIME DefaultDevicePeriod;
466 REFERENCE_TIME MinimumDevicePeriod;
467
468 // Default format (setup through Control Panel by user)
469 WAVEFORMATEXTENSIBLE DefaultFormat;
470
471 // Mix format (internal format used by WASAPI audio engine)
472 WAVEFORMATEXTENSIBLE MixFormat;
473
474 // Fields filled from IMMEndpoint'sGetDataFlow
475 EDataFlow flow;
476
477 // Form-factor
478 EndpointFormFactor formFactor;
479 }
480 PaWasapiDeviceInfo;
481
482 // ------------------------------------------------------------------------------------------
483 /* PaWasapiHostApiRepresentation - host api datastructure specific to this implementation */
484 typedef struct
485 {
486 PaUtilHostApiRepresentation inheritedHostApiRep;
487 PaUtilStreamInterface callbackStreamInterface;
488 PaUtilStreamInterface blockingStreamInterface;
489
490 PaUtilAllocationGroup *allocations;
491
492 /* implementation specific data goes here */
493
494 PaWinUtilComInitializationResult comInitializationResult;
495
496 // this is the REAL number of devices, whether they are useful to PA or not!
497 UINT32 deviceCount;
498
499 PaWasapiDeviceInfo *devInfo;
500
501 // is TRUE when WOW64 Vista/7 Workaround is needed
502 BOOL useWOW64Workaround;
503 }
504 PaWasapiHostApiRepresentation;
505
506 // ------------------------------------------------------------------------------------------
507 /* PaWasapiAudioClientParams - audio client parameters */
508 typedef struct PaWasapiAudioClientParams
509 {
510 PaWasapiDeviceInfo *device_info;
511 PaStreamParameters stream_params;
512 PaWasapiStreamInfo wasapi_params;
513 UINT32 frames_per_buffer;
514 double sample_rate;
515 BOOL blocking;
516 BOOL full_duplex;
517 BOOL wow64_workaround;
518 }
519 PaWasapiAudioClientParams;
520
521 // ------------------------------------------------------------------------------------------
522 /* PaWasapiStream - a stream data structure specifically for this implementation */
523 typedef struct PaWasapiSubStream
524 {
525 IAudioClient *clientParent;
526 #ifndef PA_WINRT
527 IStream *clientStream;
528 #endif
529 IAudioClient *clientProc;
530
531 WAVEFORMATEXTENSIBLE wavex;
532 UINT32 bufferSize;
533 REFERENCE_TIME deviceLatency;
534 REFERENCE_TIME period;
535 double latencySeconds;
536 UINT32 framesPerHostCallback;
537 AUDCLNT_SHAREMODE shareMode;
538 UINT32 streamFlags; // AUDCLNT_STREAMFLAGS_EVENTCALLBACK, ...
539 UINT32 flags;
540 PaWasapiAudioClientParams params; //!< parameters
541
542 // Buffers
543 UINT32 buffers; //!< number of buffers used (from host side)
544 UINT32 framesPerBuffer; //!< number of frames per 1 buffer
545 BOOL userBufferAndHostMatch;
546
547 // Used for Mono >> Stereo workaround, if driver does not support it
548 // (in Exclusive mode WASAPI usually refuses to operate with Mono (1-ch)
549 void *monoBuffer; //!< pointer to buffer
550 UINT32 monoBufferSize; //!< buffer size in bytes
551 MixMonoToStereoF monoMixer; //!< pointer to mixer function
552
553 PaUtilRingBuffer *tailBuffer; //!< buffer with trailing sample for blocking mode operations (only for Input)
554 void *tailBufferMemory; //!< tail buffer memory region
555 }
556 PaWasapiSubStream;
557
558 // ------------------------------------------------------------------------------------------
559 /* PaWasapiHostProcessor - redirects processing data */
560 typedef struct PaWasapiHostProcessor
561 {
562 PaWasapiHostProcessorCallback processor;
563 void *userData;
564 }
565 PaWasapiHostProcessor;
566
567 // ------------------------------------------------------------------------------------------
568 typedef struct PaWasapiStream
569 {
570 /* IMPLEMENT ME: rename this */
571 PaUtilStreamRepresentation streamRepresentation;
572 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
573 PaUtilBufferProcessor bufferProcessor;
574
575 // input
576 PaWasapiSubStream in;
577 IAudioCaptureClient *captureClientParent;
578 #ifndef PA_WINRT
579 IStream *captureClientStream;
580 #endif
581 IAudioCaptureClient *captureClient;
582 IAudioEndpointVolume *inVol;
583
584 // output
585 PaWasapiSubStream out;
586 IAudioRenderClient *renderClientParent;
587 #ifndef PA_WINRT
588 IStream *renderClientStream;
589 #endif
590 IAudioRenderClient *renderClient;
591 IAudioEndpointVolume *outVol;
592
593 // event handles for event-driven processing mode
594 HANDLE event[S_COUNT];
595
596 // buffer mode
597 PaUtilHostBufferSizeMode bufferMode;
598
599 // must be volatile to avoid race condition on user query while
600 // thread is being started
601 volatile BOOL running;
602
603 PA_THREAD_ID dwThreadId;
604 HANDLE hThread;
605 HANDLE hCloseRequest;
606 HANDLE hThreadStart; //!< signalled by thread on start
607 HANDLE hThreadExit; //!< signalled by thread on exit
608 HANDLE hBlockingOpStreamRD;
609 HANDLE hBlockingOpStreamWR;
610
611 // Host callback Output overrider
612 PaWasapiHostProcessor hostProcessOverrideOutput;
613
614 // Host callback Input overrider
615 PaWasapiHostProcessor hostProcessOverrideInput;
616
617 // Defines blocking/callback interface used
618 BOOL bBlocking;
619
620 // Av Task (MM thread management)
621 HANDLE hAvTask;
622
623 // Thread priority level
624 PaWasapiThreadPriority nThreadPriority;
625
626 // State handler
627 PaWasapiStreamStateCallback fnStateHandler;
628 void *pStateHandlerUserData;
629 }
630 PaWasapiStream;
631
632 // COM marshaling
633 static HRESULT MarshalSubStreamComPointers(PaWasapiSubStream *substream);
634 static HRESULT MarshalStreamComPointers(PaWasapiStream *stream);
635 static HRESULT UnmarshalSubStreamComPointers(PaWasapiSubStream *substream);
636 static HRESULT UnmarshalStreamComPointers(PaWasapiStream *stream);
637 static void ReleaseUnmarshaledSubComPointers(PaWasapiSubStream *substream);
638 static void ReleaseUnmarshaledComPointers(PaWasapiStream *stream);
639
640 // Local methods
641 static void _StreamOnStop(PaWasapiStream *stream);
642 static void _StreamFinish(PaWasapiStream *stream);
643 static void _StreamCleanup(PaWasapiStream *stream);
644 static HRESULT _PollGetOutputFramesAvailable(PaWasapiStream *stream, UINT32 *available);
645 static HRESULT _PollGetInputFramesAvailable(PaWasapiStream *stream, UINT32 *available);
646 static void *PaWasapi_ReallocateMemory(void *prev, size_t size);
647 static void PaWasapi_FreeMemory(void *ptr);
648 static PaSampleFormat WaveToPaFormat(const WAVEFORMATEXTENSIBLE *fmtext);
649
650 // WinRT (UWP) device list
651 #ifdef PA_WINRT
652 typedef struct PaWasapiWinrtDeviceInfo
653 {
654 WCHAR id[PA_WASAPI_DEVICE_ID_LEN];
655 WCHAR name[PA_WASAPI_DEVICE_NAME_LEN];
656 EndpointFormFactor formFactor;
657 }
658 PaWasapiWinrtDeviceInfo;
659 typedef struct PaWasapiWinrtDeviceListRole
660 {
661 WCHAR defaultId[PA_WASAPI_DEVICE_ID_LEN];
662 PaWasapiWinrtDeviceInfo devices[PA_WASAPI_DEVICE_MAX_COUNT];
663 UINT32 deviceCount;
664 }
665 PaWasapiWinrtDeviceListRole;
666 typedef struct PaWasapiWinrtDeviceList
667 {
668 PaWasapiWinrtDeviceListRole render;
669 PaWasapiWinrtDeviceListRole capture;
670 }
671 PaWasapiWinrtDeviceList;
672 static PaWasapiWinrtDeviceList g_DeviceListInfo = { 0 };
673 #endif
674
675 // WinRT (UWP) device list context
676 #ifdef PA_WINRT
677 typedef struct PaWasapiWinrtDeviceListContextEntry
678 {
679 PaWasapiWinrtDeviceInfo *info;
680 EDataFlow flow;
681 }
682 PaWasapiWinrtDeviceListContextEntry;
683 typedef struct PaWasapiWinrtDeviceListContext
684 {
685 PaWasapiWinrtDeviceListContextEntry devices[PA_WASAPI_DEVICE_MAX_COUNT * 2];
686 }
687 PaWasapiWinrtDeviceListContext;
688 #endif
689
690 // ------------------------------------------------------------------------------------------
691 #define LogHostError(HRES) __LogHostError(HRES, __FUNCTION__, __FILE__, __LINE__)
692 static HRESULT __LogHostError(HRESULT res, const char *func, const char *file, int line)
693 {
694 const char *text = NULL;
695 switch (res)
696 {
697 case S_OK: return res;
698 case E_POINTER :text ="E_POINTER"; break;
699 case E_INVALIDARG :text ="E_INVALIDARG"; break;
700
701 case AUDCLNT_E_NOT_INITIALIZED :text ="AUDCLNT_E_NOT_INITIALIZED"; break;
702 case AUDCLNT_E_ALREADY_INITIALIZED :text ="AUDCLNT_E_ALREADY_INITIALIZED"; break;
703 case AUDCLNT_E_WRONG_ENDPOINT_TYPE :text ="AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
704 case AUDCLNT_E_DEVICE_INVALIDATED :text ="AUDCLNT_E_DEVICE_INVALIDATED"; break;
705 case AUDCLNT_E_NOT_STOPPED :text ="AUDCLNT_E_NOT_STOPPED"; break;
706 case AUDCLNT_E_BUFFER_TOO_LARGE :text ="AUDCLNT_E_BUFFER_TOO_LARGE"; break;
707 case AUDCLNT_E_OUT_OF_ORDER :text ="AUDCLNT_E_OUT_OF_ORDER"; break;
708 case AUDCLNT_E_UNSUPPORTED_FORMAT :text ="AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
709 case AUDCLNT_E_INVALID_SIZE :text ="AUDCLNT_E_INVALID_SIZE"; break;
710 case AUDCLNT_E_DEVICE_IN_USE :text ="AUDCLNT_E_DEVICE_IN_USE"; break;
711 case AUDCLNT_E_BUFFER_OPERATION_PENDING :text ="AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
712 case AUDCLNT_E_THREAD_NOT_REGISTERED :text ="AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
713 case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED :text ="AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
714 case AUDCLNT_E_ENDPOINT_CREATE_FAILED :text ="AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
715 case AUDCLNT_E_SERVICE_NOT_RUNNING :text ="AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
716 case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED :text ="AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
717 case AUDCLNT_E_EXCLUSIVE_MODE_ONLY :text ="AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
718 case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL :text ="AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
719 case AUDCLNT_E_EVENTHANDLE_NOT_SET :text ="AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
720 case AUDCLNT_E_INCORRECT_BUFFER_SIZE :text ="AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
721 case AUDCLNT_E_BUFFER_SIZE_ERROR :text ="AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
722 case AUDCLNT_E_CPUUSAGE_EXCEEDED :text ="AUDCLNT_E_CPUUSAGE_EXCEEDED"; break;
723 case AUDCLNT_E_BUFFER_ERROR :text ="AUDCLNT_E_BUFFER_ERROR"; break;
724 case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED :text ="AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED"; break;
725 case AUDCLNT_E_INVALID_DEVICE_PERIOD :text ="AUDCLNT_E_INVALID_DEVICE_PERIOD"; break;
726
727 #ifdef AUDCLNT_E_INVALID_STREAM_FLAG
728 case AUDCLNT_E_INVALID_STREAM_FLAG :text ="AUDCLNT_E_INVALID_STREAM_FLAG"; break;
729 #endif
730 #ifdef AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE
731 case AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE :text ="AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE"; break;
732 #endif
733 #ifdef AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES
734 case AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES :text ="AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES"; break;
735 #endif
736 #ifdef AUDCLNT_E_OFFLOAD_MODE_ONLY
737 case AUDCLNT_E_OFFLOAD_MODE_ONLY :text ="AUDCLNT_E_OFFLOAD_MODE_ONLY"; break;
738 #endif
739 #ifdef AUDCLNT_E_NONOFFLOAD_MODE_ONLY
740 case AUDCLNT_E_NONOFFLOAD_MODE_ONLY :text ="AUDCLNT_E_NONOFFLOAD_MODE_ONLY"; break;
741 #endif
742 #ifdef AUDCLNT_E_RESOURCES_INVALIDATED
743 case AUDCLNT_E_RESOURCES_INVALIDATED :text ="AUDCLNT_E_RESOURCES_INVALIDATED"; break;
744 #endif
745 #ifdef AUDCLNT_E_RAW_MODE_UNSUPPORTED
746 case AUDCLNT_E_RAW_MODE_UNSUPPORTED :text ="AUDCLNT_E_RAW_MODE_UNSUPPORTED"; break;
747 #endif
748 #ifdef AUDCLNT_E_ENGINE_PERIODICITY_LOCKED
749 case AUDCLNT_E_ENGINE_PERIODICITY_LOCKED :text ="AUDCLNT_E_ENGINE_PERIODICITY_LOCKED"; break;
750 #endif
751 #ifdef AUDCLNT_E_ENGINE_FORMAT_LOCKED
752 case AUDCLNT_E_ENGINE_FORMAT_LOCKED :text ="AUDCLNT_E_ENGINE_FORMAT_LOCKED"; break;
753 #endif
754
755 case AUDCLNT_S_BUFFER_EMPTY :text ="AUDCLNT_S_BUFFER_EMPTY"; break;
756 case AUDCLNT_S_THREAD_ALREADY_REGISTERED :text ="AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
757 case AUDCLNT_S_POSITION_STALLED :text ="AUDCLNT_S_POSITION_STALLED"; break;
758
759 // other windows common errors:
760 case CO_E_NOTINITIALIZED :text ="CO_E_NOTINITIALIZED: you must call CoInitialize() before Pa_OpenStream()"; break;
761
762 default:
763 text = "UNKNOWN ERROR";
764 }
765 PRINT(("WASAPI ERROR HRESULT: 0x%X : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", res, text, func, file, line));
766 #ifndef PA_ENABLE_DEBUG_OUTPUT
767 (void)func; (void)file; (void)line;
768 #endif
769 PA_SKELETON_SET_LAST_HOST_ERROR(res, text);
770 return res;
771 }
772
773 // ------------------------------------------------------------------------------------------
774 #define LogPaError(PAERR) __LogPaError(PAERR, __FUNCTION__, __FILE__, __LINE__)
775 static PaError __LogPaError(PaError err, const char *func, const char *file, int line)
776 {
777 if (err == paNoError)
778 return err;
779
780 PRINT(("WASAPI ERROR PAERROR: %i : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", err, Pa_GetErrorText(err), func, file, line));
781 #ifndef PA_ENABLE_DEBUG_OUTPUT
782 (void)func; (void)file; (void)line;
783 #endif
784 return err;
785 }
786
787 // ------------------------------------------------------------------------------------------
788 /*! \class ThreadSleepScheduler
789 Allows to emulate thread sleep of less than 1 millisecond under Windows. Scheduler
790 calculates number of times the thread must run until next sleep of 1 millisecond.
791 It does not make thread sleeping for real number of microseconds but rather controls
792 how many of imaginary microseconds the thread task can allow thread to sleep.
793 */
794 typedef struct ThreadIdleScheduler
795 {
796 UINT32 m_idle_microseconds; //!< number of microseconds to sleep
797 UINT32 m_next_sleep; //!< next sleep round
798 UINT32 m_i; //!< current round iterator position
799 UINT32 m_resolution; //!< resolution in number of milliseconds
800 }
801 ThreadIdleScheduler;
802
803 //! Setup scheduler.
804 static void ThreadIdleScheduler_Setup(ThreadIdleScheduler *sched, UINT32 resolution, UINT32 microseconds)
805 {
806 assert(microseconds != 0);
807 assert(resolution != 0);
808 assert((resolution * 1000) >= microseconds);
809
810 memset(sched, 0, sizeof(*sched));
811
812 sched->m_idle_microseconds = microseconds;
813 sched->m_resolution = resolution;
814 sched->m_next_sleep = (resolution * 1000) / microseconds;
815 }
816
817 //! Iterate and check if can sleep.
818 static inline UINT32 ThreadIdleScheduler_NextSleep(ThreadIdleScheduler *sched)
819 {
820 // advance and check if thread can sleep
821 if (++sched->m_i == sched->m_next_sleep)
822 {
823 sched->m_i = 0;
824 return sched->m_resolution;
825 }
826 return 0;
827 }
828
829 // ------------------------------------------------------------------------------------------
830 typedef struct _SystemTimer
831 {
832 INT32 granularity;
833
834 } SystemTimer;
835 static LARGE_INTEGER g_SystemTimerFrequency;
836 static BOOL g_SystemTimerUseQpc = FALSE;
837
838 //! Set granularity of the system timer.
839 static BOOL SystemTimer_SetGranularity(SystemTimer *timer, UINT32 granularity)
840 {
841 #ifndef PA_WINRT
842 TIMECAPS caps;
843
844 timer->granularity = granularity;
845
846 if (timeGetDevCaps(&caps, sizeof(caps)) == MMSYSERR_NOERROR)
847 {
848 if (timer->granularity < (INT32)caps.wPeriodMin)
849 timer->granularity = (INT32)caps.wPeriodMin;
850 }
851
852 if (timeBeginPeriod(timer->granularity) != TIMERR_NOERROR)
853 {
854 PRINT(("SetSystemTimer: timeBeginPeriod(1) failed!\n"));
855
856 timer->granularity = 10;
857 return FALSE;
858 }
859 #else
860 (void)granularity;
861
862 // UWP does not support increase of the timer precision change and thus calling WaitForSingleObject with anything
863 // below 10 milliseconds will cause underruns for input and output stream.
864 timer->granularity = 10;
865 #endif
866
867 return TRUE;
868 }
869
870 //! Restore granularity of the system timer.
871 static void SystemTimer_RestoreGranularity(SystemTimer *timer)
872 {
873 #ifndef PA_WINRT
874 if (timer->granularity != 0)
875 {
876 if (timeEndPeriod(timer->granularity) != TIMERR_NOERROR)
877 {
878 PRINT(("RestoreSystemTimer: timeEndPeriod(1) failed!\n"));
879 }
880 }
881 #else
882 (void)timer;
883 #endif
884 }
885
886 //! Initialize high-resolution time getter.
887 static void SystemTimer_InitializeTimeGetter()
888 {
889 g_SystemTimerUseQpc = QueryPerformanceFrequency(&g_SystemTimerFrequency);
890 }
891
892 //! Get high-resolution time in milliseconds (using QPC by default).
893 static inline LONGLONG SystemTimer_GetTime(SystemTimer *timer)
894 {
895 (void)timer;
896
897 // QPC: https://docs.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps
898 if (g_SystemTimerUseQpc)
899 {
900 LARGE_INTEGER now;
901 QueryPerformanceCounter(&now);
902 return (now.QuadPart * 1000LL) / g_SystemTimerFrequency.QuadPart;
903 }
904 else
905 {
906 #ifdef PA_WINRT
907 return GetTickCount64();
908 #else
909 return timeGetTime();
910 #endif
911 }
912 }
913
914 // ------------------------------------------------------------------------------------------
915 /*static double nano100ToMillis(REFERENCE_TIME ref)
916 {
917 // 1 nano = 0.000000001 seconds
918 //100 nano = 0.0000001 seconds
919 //100 nano = 0.0001 milliseconds
920 return ((double)ref) * 0.0001;
921 }*/
922
923 // ------------------------------------------------------------------------------------------
924 static double nano100ToSeconds(REFERENCE_TIME ref)
925 {
926 // 1 nano = 0.000000001 seconds
927 //100 nano = 0.0000001 seconds
928 //100 nano = 0.0001 milliseconds
929 return ((double)ref) * 0.0000001;
930 }
931
932 // ------------------------------------------------------------------------------------------
933 /*static REFERENCE_TIME MillisTonano100(double ref)
934 {
935 // 1 nano = 0.000000001 seconds
936 //100 nano = 0.0000001 seconds
937 //100 nano = 0.0001 milliseconds
938 return (REFERENCE_TIME)(ref / 0.0001);
939 }*/
940
941 // ------------------------------------------------------------------------------------------
942 static REFERENCE_TIME SecondsTonano100(double ref)
943 {
944 // 1 nano = 0.000000001 seconds
945 //100 nano = 0.0000001 seconds
946 //100 nano = 0.0001 milliseconds
947 return (REFERENCE_TIME)(ref / 0.0000001);
948 }
949
950 // ------------------------------------------------------------------------------------------
951 // Makes Hns period from frames and sample rate
952 static REFERENCE_TIME MakeHnsPeriod(UINT32 nFrames, DWORD nSamplesPerSec)
953 {
954 return (REFERENCE_TIME)((10000.0 * 1000 / nSamplesPerSec * nFrames) + 0.5);
955 }
956
957 // ------------------------------------------------------------------------------------------
958 // Converts PaSampleFormat to bits per sample value
959 // Note: paCustomFormat stands for 8.24 format (24-bits inside 32-bit containers)
960 static WORD PaSampleFormatToBitsPerSample(PaSampleFormat format_id)
961 {
962 switch (format_id & ~paNonInterleaved)
963 {
964 case paFloat32:
965 case paInt32: return 32;
966 case paCustomFormat:
967 case paInt24: return 24;
968 case paInt16: return 16;
969 case paInt8:
970 case paUInt8: return 8;
971 }
972 return 0;
973 }
974
975 // ------------------------------------------------------------------------------------------
976 // Convert PaSampleFormat to valid sample format for I/O, e.g. if paCustomFormat is specified
977 // it will be converted to paInt32, other formats pass through
978 // Note: paCustomFormat stands for 8.24 format (24-bits inside 32-bit containers)
979 static PaSampleFormat GetSampleFormatForIO(PaSampleFormat format_id)
980 {
981 return ((format_id & ~paNonInterleaved) == paCustomFormat ?
982 (paInt32 | (format_id & paNonInterleaved ? paNonInterleaved : 0)) : format_id);
983 }
984
985 // ------------------------------------------------------------------------------------------
986 // Converts Hns period into number of frames
987 static UINT32 MakeFramesFromHns(REFERENCE_TIME hnsPeriod, UINT32 nSamplesPerSec)
988 {
989 UINT32 nFrames = (UINT32)( // frames =
990 1.0 * hnsPeriod * // hns *
991 nSamplesPerSec / // (frames / s) /
992 1000 / // (ms / s) /
993 10000 // (hns / s) /
994 + 0.5 // rounding
995 );
996 return nFrames;
997 }
998
999 // Aligning function type
1000 typedef UINT32 (*ALIGN_FUNC) (UINT32 v, UINT32 align);
1001
1002 // ------------------------------------------------------------------------------------------
1003 // Aligns 'v' backwards
1004 static UINT32 ALIGN_BWD(UINT32 v, UINT32 align)
1005 {
1006 return ((v - (align ? v % align : 0)));
1007 }
1008
1009 // ------------------------------------------------------------------------------------------
1010 // Aligns 'v' forward
1011 static UINT32 ALIGN_FWD(UINT32 v, UINT32 align)
1012 {
1013 UINT32 remainder = (align ? (v % align) : 0);
1014 if (remainder == 0)
1015 return v;
1016 return v + (align - remainder);
1017 }
1018
1019 // ------------------------------------------------------------------------------------------
1020 // Get next value power of 2
1021 static UINT32 ALIGN_NEXT_POW2(UINT32 v)
1022 {
1023 UINT32 v2 = 1;
1024 while (v > (v2 <<= 1)) { }
1025 v = v2;
1026 return v;
1027 }
1028
1029 // ------------------------------------------------------------------------------------------
1030 // Aligns WASAPI buffer to 128 byte packet boundary. HD Audio will fail to play if buffer
1031 // is misaligned. This problem was solved in Windows 7 were AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
1032 // is thrown although we must align for Vista anyway.
1033 static UINT32 AlignFramesPerBuffer(UINT32 nFrames, UINT32 nBlockAlign, ALIGN_FUNC pAlignFunc)
1034 {
1035 #define HDA_PACKET_SIZE (128)
1036
1037 UINT32 bytes = nFrames * nBlockAlign;
1038 UINT32 packets;
1039
1040 // align to a HD Audio packet size
1041 bytes = pAlignFunc(bytes, HDA_PACKET_SIZE);
1042
1043 // atlest 1 frame must be available
1044 if (bytes < HDA_PACKET_SIZE)
1045 bytes = HDA_PACKET_SIZE;
1046
1047 packets = bytes / HDA_PACKET_SIZE;
1048 bytes = packets * HDA_PACKET_SIZE;
1049 nFrames = bytes / nBlockAlign;
1050
1051 // WASAPI frames are always aligned to at least 8
1052 nFrames = ALIGN_FWD(nFrames, 8);
1053
1054 return nFrames;
1055
1056 #undef HDA_PACKET_SIZE
1057 }
1058
1059 // ------------------------------------------------------------------------------------------
1060 static UINT32 GetFramesSleepTime(REFERENCE_TIME nFrames, REFERENCE_TIME nSamplesPerSec)
1061 {
1062 REFERENCE_TIME nDuration;
1063 if (nSamplesPerSec == 0)
1064 return 0;
1065
1066 #define REFTIMES_PER_SEC 10000000LL
1067 #define REFTIMES_PER_MILLISEC 10000LL
1068
1069 // Calculate the actual duration of the allocated buffer.
1070 nDuration = (REFTIMES_PER_SEC * nFrames) / nSamplesPerSec;
1071 return (UINT32)(nDuration / REFTIMES_PER_MILLISEC);
1072
1073 #undef REFTIMES_PER_SEC
1074 #undef REFTIMES_PER_MILLISEC
1075 }
1076
1077 // ------------------------------------------------------------------------------------------
1078 static UINT32 GetFramesSleepTimeMicroseconds(REFERENCE_TIME nFrames, REFERENCE_TIME nSamplesPerSec)
1079 {
1080 REFERENCE_TIME nDuration;
1081 if (nSamplesPerSec == 0)
1082 return 0;
1083
1084 #define REFTIMES_PER_SEC 10000000LL
1085 #define REFTIMES_PER_MILLISEC 10000LL
1086
1087 // Calculate the actual duration of the allocated buffer.
1088 nDuration = (REFTIMES_PER_SEC * nFrames) / nSamplesPerSec;
1089 return (UINT32)(nDuration / 10);
1090
1091 #undef REFTIMES_PER_SEC
1092 #undef REFTIMES_PER_MILLISEC
1093 }
1094
1095 // ------------------------------------------------------------------------------------------
1096 #ifndef PA_WINRT
1097 static BOOL SetupAVRT()
1098 {
1099 hDInputDLL = LoadLibraryA("avrt.dll");
1100 if (hDInputDLL == NULL)
1101 return FALSE;
1102
1103 _GetProc(pAvRtCreateThreadOrderingGroup, FAvRtCreateThreadOrderingGroup, "AvRtCreateThreadOrderingGroup");
1104 _GetProc(pAvRtDeleteThreadOrderingGroup, FAvRtDeleteThreadOrderingGroup, "AvRtDeleteThreadOrderingGroup");
1105 _GetProc(pAvRtWaitOnThreadOrderingGroup, FAvRtWaitOnThreadOrderingGroup, "AvRtWaitOnThreadOrderingGroup");
1106 _GetProc(pAvSetMmThreadCharacteristics, FAvSetMmThreadCharacteristics, "AvSetMmThreadCharacteristicsA");
1107 _GetProc(pAvRevertMmThreadCharacteristics,FAvRevertMmThreadCharacteristics,"AvRevertMmThreadCharacteristics");
1108 _GetProc(pAvSetMmThreadPriority, FAvSetMmThreadPriority, "AvSetMmThreadPriority");
1109
1110 return pAvRtCreateThreadOrderingGroup &&
1111 pAvRtDeleteThreadOrderingGroup &&
1112 pAvRtWaitOnThreadOrderingGroup &&
1113 pAvSetMmThreadCharacteristics &&
1114 pAvRevertMmThreadCharacteristics &&
1115 pAvSetMmThreadPriority;
1116 }
1117 #endif
1118
1119 // ------------------------------------------------------------------------------------------
1120 static void CloseAVRT()
1121 {
1122 #ifndef PA_WINRT
1123 if (hDInputDLL != NULL)
1124 FreeLibrary(hDInputDLL);
1125 hDInputDLL = NULL;
1126 #endif
1127 }
1128
1129 // ------------------------------------------------------------------------------------------
1130 static BOOL IsWow64()
1131 {
1132 #ifndef PA_WINRT
1133
1134 // http://msdn.microsoft.com/en-us/library/ms684139(VS.85).aspx
1135
1136 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
1137 LPFN_ISWOW64PROCESS fnIsWow64Process;
1138
1139 BOOL bIsWow64 = FALSE;
1140
1141 // IsWow64Process is not available on all supported versions of Windows.
1142 // Use GetModuleHandle to get a handle to the DLL that contains the function
1143 // and GetProcAddress to get a pointer to the function if available.
1144
1145 fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
1146 GetModuleHandleA("kernel32"), "IsWow64Process");
1147
1148 if (fnIsWow64Process == NULL)
1149 return FALSE;
1150
1151 if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
1152 return FALSE;
1153
1154 return bIsWow64;
1155
1156 #else
1157
1158 return FALSE;
1159
1160 #endif
1161 }
1162
1163 // ------------------------------------------------------------------------------------------
1164 typedef enum EWindowsVersion
1165 {
1166 WINDOWS_UNKNOWN = 0,
1167 WINDOWS_VISTA_SERVER2008,
1168 WINDOWS_7_SERVER2008R2,
1169 WINDOWS_8_SERVER2012,
1170 WINDOWS_8_1_SERVER2012R2,
1171 WINDOWS_10_SERVER2016,
1172 WINDOWS_FUTURE
1173 }
1174 EWindowsVersion;
1175 // Alternative way for checking Windows version (allows to check version on Windows 8.1 and up)
1176 #ifndef PA_WINRT
1177 static BOOL IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor)
1178 {
1179 typedef ULONGLONG (NTAPI *LPFN_VERSETCONDITIONMASK)(ULONGLONG ConditionMask, DWORD TypeMask, BYTE Condition);
1180 typedef BOOL (WINAPI *LPFN_VERIFYVERSIONINFO)(LPOSVERSIONINFOEXA lpVersionInformation, DWORD dwTypeMask, DWORDLONG dwlConditionMask);
1181
1182 LPFN_VERSETCONDITIONMASK fnVerSetConditionMask;
1183 LPFN_VERIFYVERSIONINFO fnVerifyVersionInfo;
1184 OSVERSIONINFOEXA osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
1185 DWORDLONG dwlConditionMask;
1186
1187 fnVerSetConditionMask = (LPFN_VERSETCONDITIONMASK)GetProcAddress(GetModuleHandleA("kernel32"), "VerSetConditionMask");
1188 fnVerifyVersionInfo = (LPFN_VERIFYVERSIONINFO)GetProcAddress(GetModuleHandleA("kernel32"), "VerifyVersionInfoA");
1189
1190 if ((fnVerSetConditionMask == NULL) || (fnVerifyVersionInfo == NULL))
1191 return FALSE;
1192
1193 dwlConditionMask = fnVerSetConditionMask(
1194 fnVerSetConditionMask(
1195 fnVerSetConditionMask(
1196 0, VER_MAJORVERSION, VER_GREATER_EQUAL),
1197 VER_MINORVERSION, VER_GREATER_EQUAL),
1198 VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
1199
1200 osvi.dwMajorVersion = wMajorVersion;
1201 osvi.dwMinorVersion = wMinorVersion;
1202 osvi.wServicePackMajor = wServicePackMajor;
1203
1204 return (fnVerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE);
1205 }
1206 #endif
1207 // Get Windows version
1208 static EWindowsVersion GetWindowsVersion()
1209 {
1210 #ifndef PA_WINRT
1211 static EWindowsVersion version = WINDOWS_UNKNOWN;
1212
1213 if (version == WINDOWS_UNKNOWN)
1214 {
1215 DWORD dwMajorVersion = 0xFFFFFFFFU, dwMinorVersion = 0, dwBuild = 0;
1216
1217 // RTL_OSVERSIONINFOW equals OSVERSIONINFOW but it is missing inb MinGW winnt.h header,
1218 // thus use OSVERSIONINFOW for greater portability
1219 typedef NTSTATUS (WINAPI *LPFN_RTLGETVERSION)(POSVERSIONINFOW lpVersionInformation);
1220 LPFN_RTLGETVERSION fnRtlGetVersion;
1221
1222 #define NTSTATUS_SUCCESS ((NTSTATUS)0x00000000L)
1223
1224 // RtlGetVersion must be able to provide true Windows version (Windows 10 may be reported as Windows 8
1225 // by GetVersion API)
1226 if ((fnRtlGetVersion = (LPFN_RTLGETVERSION)GetProcAddress(GetModuleHandleA("ntdll"), "RtlGetVersion")) != NULL)
1227 {
1228 OSVERSIONINFOW ver = { sizeof(OSVERSIONINFOW), 0, 0, 0, 0, {0} };
1229
1230 PRINT(("WASAPI: getting Windows version with RtlGetVersion()\n"));
1231
1232 if (fnRtlGetVersion(&ver) == NTSTATUS_SUCCESS)
1233 {
1234 dwMajorVersion = ver.dwMajorVersion;
1235 dwMinorVersion = ver.dwMinorVersion;
1236 dwBuild = ver.dwBuildNumber;
1237 }
1238 }
1239
1240 #undef NTSTATUS_SUCCESS
1241
1242 // fallback to GetVersion if RtlGetVersion is missing
1243 if (dwMajorVersion == 0xFFFFFFFFU)
1244 {
1245 typedef DWORD (WINAPI *LPFN_GETVERSION)(VOID);
1246 LPFN_GETVERSION fnGetVersion;
1247
1248 if ((fnGetVersion = (LPFN_GETVERSION)GetProcAddress(GetModuleHandleA("kernel32"), "GetVersion")) != NULL)
1249 {
1250 DWORD dwVersion;
1251
1252 PRINT(("WASAPI: getting Windows version with GetVersion()\n"));
1253
1254 dwVersion = fnGetVersion();
1255
1256 dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
1257 dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
1258
1259 if (dwVersion < 0x80000000)
1260 dwBuild = (DWORD)(HIWORD(dwVersion));
1261 }
1262 }
1263
1264 if (dwMajorVersion != 0xFFFFFFFFU)
1265 {
1266 switch (dwMajorVersion)
1267 {
1268 case 0:
1269 case 1:
1270 case 2:
1271 case 3:
1272 case 4:
1273 case 5:
1274 break; // skip lower
1275 case 6:
1276 switch (dwMinorVersion)
1277 {
1278 case 0: version = WINDOWS_VISTA_SERVER2008; break;
1279 case 1: version = WINDOWS_7_SERVER2008R2; break;
1280 case 2: version = WINDOWS_8_SERVER2012; break;
1281 case 3: version = WINDOWS_8_1_SERVER2012R2; break;
1282 default: version = WINDOWS_FUTURE; break;
1283 }
1284 break;
1285 case 10:
1286 switch (dwMinorVersion)
1287 {
1288 case 0: version = WINDOWS_10_SERVER2016; break;
1289 default: version = WINDOWS_FUTURE; break;
1290 }
1291 break;
1292 default:
1293 version = WINDOWS_FUTURE;
1294 break;
1295 }
1296 }
1297 // fallback to VerifyVersionInfo if RtlGetVersion and GetVersion are missing
1298 else
1299 {
1300 PRINT(("WASAPI: getting Windows version with VerifyVersionInfo()\n"));
1301
1302 if (IsWindowsVersionOrGreater(10, 0, 0))
1303 version = WINDOWS_10_SERVER2016;
1304 else
1305 if (IsWindowsVersionOrGreater(6, 3, 0))
1306 version = WINDOWS_8_1_SERVER2012R2;
1307 else
1308 if (IsWindowsVersionOrGreater(6, 2, 0))
1309 version = WINDOWS_8_SERVER2012;
1310 else
1311 if (IsWindowsVersionOrGreater(6, 1, 0))
1312 version = WINDOWS_7_SERVER2008R2;
1313 else
1314 if (IsWindowsVersionOrGreater(6, 0, 0))
1315 version = WINDOWS_VISTA_SERVER2008;
1316 else
1317 version = WINDOWS_FUTURE;
1318 }
1319
1320 PRINT(("WASAPI: Windows version = %d\n", version));
1321 }
1322
1323 return version;
1324 #else
1325 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN10)
1326 return WINDOWS_10_SERVER2016;
1327 #else
1328 return WINDOWS_8_SERVER2012;
1329 #endif
1330 #endif
1331 }
1332
1333 // ------------------------------------------------------------------------------------------
1334 static BOOL UseWOW64Workaround()
1335 {
1336 // note: WOW64 bug is common to Windows Vista x64, thus we fall back to safe Poll-driven
1337 // method. Windows 7 x64 seems has WOW64 bug fixed.
1338
1339 return (IsWow64() && (GetWindowsVersion() == WINDOWS_VISTA_SERVER2008));
1340 }
1341
1342 // ------------------------------------------------------------------------------------------
1343 static UINT32 GetAudioClientVersion()
1344 {
1345 if (GetWindowsVersion() >= WINDOWS_10_SERVER2016)
1346 return 3;
1347 else
1348 if (GetWindowsVersion() >= WINDOWS_8_SERVER2012)
1349 return 2;
1350
1351 return 1;
1352 }
1353
1354 // ------------------------------------------------------------------------------------------
1355 static const IID *GetAudioClientIID()
1356 {
1357 static const IID *cli_iid = NULL;
1358 if (cli_iid == NULL)
1359 {
1360 UINT32 cli_version = GetAudioClientVersion();
1361 switch (cli_version)
1362 {
1363 case 3: cli_iid = &pa_IID_IAudioClient3; break;
1364 case 2: cli_iid = &pa_IID_IAudioClient2; break;
1365 default: cli_iid = &pa_IID_IAudioClient; break;
1366 }
1367
1368 PRINT(("WASAPI: IAudioClient version = %d\n", cli_version));
1369 }
1370
1371 return cli_iid;
1372 }
1373
1374 // ------------------------------------------------------------------------------------------
1375 typedef enum EMixDirection
1376 {
1377 MIX_DIR__1TO2, //!< mix one channel to L and R
1378 MIX_DIR__2TO1, //!< mix L and R channels to one channel
1379 MIX_DIR__2TO1_L //!< mix only L channel (of total 2 channels) to one channel
1380 }
1381 EMixDirection;
1382
1383 // ------------------------------------------------------------------------------------------
1384 #define _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(TYPE)\
1385 TYPE * __restrict to = (TYPE *)__to;\
1386 const TYPE * __restrict from = (const TYPE *)__from;\
1387 const TYPE * __restrict end = from + count;\
1388 while (from != end)\
1389 {\
1390 to[0] = to[1] = *from ++;\
1391 to += 2;\
1392 }
1393
1394 // ------------------------------------------------------------------------------------------
1395 #define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_FLT32(TYPE)\
1396 TYPE * __restrict to = (TYPE *)__to;\
1397 const TYPE * __restrict from = (const TYPE *)__from;\
1398 const TYPE * __restrict end = to + count;\
1399 while (to != end)\
1400 {\
1401 *to ++ = (TYPE)((float)(from[0] + from[1]) * 0.5f);\
1402 from += 2;\
1403 }
1404
1405 // ------------------------------------------------------------------------------------------
1406 #define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(TYPE)\
1407 TYPE * __restrict to = (TYPE *)__to;\
1408 const TYPE * __restrict from = (const TYPE *)__from;\
1409 const TYPE * __restrict end = to + count;\
1410 while (to != end)\
1411 {\
1412 *to ++ = (TYPE)(((INT32)from[0] + (INT32)from[1]) >> 1);\
1413 from += 2;\
1414 }
1415
1416 // ------------------------------------------------------------------------------------------
1417 #define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT64(TYPE)\
1418 TYPE * __restrict to = (TYPE *)__to;\
1419 const TYPE * __restrict from = (const TYPE *)__from;\
1420 const TYPE * __restrict end = to + count;\
1421 while (to != end)\
1422 {\
1423 *to ++ = (TYPE)(((INT64)from[0] + (INT64)from[1]) >> 1);\
1424 from += 2;\
1425 }
1426
1427 // ------------------------------------------------------------------------------------------
1428 #define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(TYPE)\
1429 TYPE * __restrict to = (TYPE *)__to;\
1430 const TYPE * __restrict from = (const TYPE *)__from;\
1431 const TYPE * __restrict end = to + count;\
1432 while (to != end)\
1433 {\
1434 *to ++ = from[0];\
1435 from += 2;\
1436 }
1437
1438 // ------------------------------------------------------------------------------------------
1439 static void _MixMonoToStereo_1TO2_8(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(BYTE); }
1440 static void _MixMonoToStereo_1TO2_16(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(short); }
1441 static void _MixMonoToStereo_1TO2_8_24(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); /* !!! int24 data is contained in 32-bit containers*/ }
1442 static void _MixMonoToStereo_1TO2_32(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); }
1443 static void _MixMonoToStereo_1TO2_32f(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(float); }
1444 static void _MixMonoToStereo_1TO2_24(void *__to, const void *__from, UINT32 count)
1445 {
1446 const UCHAR * __restrict from = (const UCHAR *)__from;
1447 UCHAR * __restrict to = (UCHAR *)__to;
1448 const UCHAR * __restrict end = to + (count * (2 * 3));
1449
1450 while (to != end)
1451 {
1452 to[0] = to[3] = from[0];
1453 to[1] = to[4] = from[1];
1454 to[2] = to[5] = from[2];
1455
1456 from += 3;
1457 to += (2 * 3);
1458 }
1459 }
1460
1461 // ------------------------------------------------------------------------------------------
1462 static void _MixMonoToStereo_2TO1_8(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(BYTE); }
1463 static void _MixMonoToStereo_2TO1_16(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(short); }
1464 static void _MixMonoToStereo_2TO1_8_24(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT32(int); /* !!! int24 data is contained in 32-bit containers*/ }
1465 static void _MixMonoToStereo_2TO1_32(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_INT64(int); }
1466 static void _MixMonoToStereo_2TO1_32f(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_FLT32(float); }
1467 static void _MixMonoToStereo_2TO1_24(void *__to, const void *__from, UINT32 count)
1468 {
1469 const UCHAR * __restrict from = (const UCHAR *)__from;
1470 UCHAR * __restrict to = (UCHAR *)__to;
1471 const UCHAR * __restrict end = to + (count * 3);
1472 PaInt32 tempL, tempR, tempM;
1473
1474 while (to != end)
1475 {
1476 tempL = (((PaInt32)from[0]) << 8);
1477 tempL = tempL | (((PaInt32)from[1]) << 16);
1478 tempL = tempL | (((PaInt32)from[2]) << 24);
1479
1480 tempR = (((PaInt32)from[3]) << 8);
1481 tempR = tempR | (((PaInt32)from[4]) << 16);
1482 tempR = tempR | (((PaInt32)from[5]) << 24);
1483
1484 tempM = (tempL + tempR) >> 1;
1485
1486 to[0] = (UCHAR)(tempM >> 8);
1487 to[1] = (UCHAR)(tempM >> 16);
1488 to[2] = (UCHAR)(tempM >> 24);
1489
1490 from += (2 * 3);
1491 to += 3;
1492 }
1493 }
1494
1495 // ------------------------------------------------------------------------------------------
1496 static void _MixMonoToStereo_2TO1_8_L(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(BYTE); }
1497 static void _MixMonoToStereo_2TO1_16_L(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(short); }
1498 static void _MixMonoToStereo_2TO1_8_24_L(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(int); /* !!! int24 data is contained in 32-bit containers*/ }
1499 static void _MixMonoToStereo_2TO1_32_L(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(int); }
1500 static void _MixMonoToStereo_2TO1_32f_L(void *__to, const void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1_L(float); }
1501 static void _MixMonoToStereo_2TO1_24_L(void *__to, const void *__from, UINT32 count)
1502 {
1503 const UCHAR * __restrict from = (const UCHAR *)__from;
1504 UCHAR * __restrict to = (UCHAR *)__to;
1505 const UCHAR * __restrict end = to + (count * 3);
1506
1507 while (to != end)
1508 {
1509 to[0] = from[0];
1510 to[1] = from[1];
1511 to[2] = from[2];
1512
1513 from += (2 * 3);
1514 to += 3;
1515 }
1516 }
1517
1518 // ------------------------------------------------------------------------------------------
1519 static MixMonoToStereoF GetMonoToStereoMixer(const WAVEFORMATEXTENSIBLE *fmtext, EMixDirection dir)
1520 {
1521 PaSampleFormat format = WaveToPaFormat(fmtext);
1522
1523 switch (dir)
1524 {
1525 case MIX_DIR__1TO2:
1526 switch (format & ~paNonInterleaved)
1527 {
1528 case paUInt8: return _MixMonoToStereo_1TO2_8;
1529 case paInt16: return _MixMonoToStereo_1TO2_16;
1530 case paInt24: return (fmtext->Format.wBitsPerSample == 32 ? _MixMonoToStereo_1TO2_8_24 : _MixMonoToStereo_1TO2_24);
1531 case paInt32: return _MixMonoToStereo_1TO2_32;
1532 case paFloat32: return _MixMonoToStereo_1TO2_32f;
1533 }
1534 break;
1535
1536 case MIX_DIR__2TO1:
1537 switch (format & ~paNonInterleaved)
1538 {
1539 case paUInt8: return _MixMonoToStereo_2TO1_8;
1540 case paInt16: return _MixMonoToStereo_2TO1_16;
1541 case paInt24: return (fmtext->Format.wBitsPerSample == 32 ? _MixMonoToStereo_2TO1_8_24 : _MixMonoToStereo_2TO1_24);
1542 case paInt32: return _MixMonoToStereo_2TO1_32;
1543 case paFloat32: return _MixMonoToStereo_2TO1_32f;
1544 }
1545 break;
1546
1547 case MIX_DIR__2TO1_L:
1548 switch (format & ~paNonInterleaved)
1549 {
1550 case paUInt8: return _MixMonoToStereo_2TO1_8_L;
1551 case paInt16: return _MixMonoToStereo_2TO1_16_L;
1552 case paInt24: return (fmtext->Format.wBitsPerSample == 32 ? _MixMonoToStereo_2TO1_8_24_L : _MixMonoToStereo_2TO1_24_L);
1553 case paInt32: return _MixMonoToStereo_2TO1_32_L;
1554 case paFloat32: return _MixMonoToStereo_2TO1_32f_L;
1555 }
1556 break;
1557 }
1558
1559 return NULL;
1560 }
1561
1562 // ------------------------------------------------------------------------------------------
1563 #ifdef PA_WINRT
1564 typedef struct PaActivateAudioInterfaceCompletionHandler
1565 {
1566 IActivateAudioInterfaceCompletionHandler parent;
1567 volatile LONG refs;
1568 volatile LONG done;
1569 struct
1570 {
1571 const IID *iid;
1572 void **obj;
1573 }
1574 in;
1575 struct
1576 {
1577 HRESULT hr;
1578 }
1579 out;
1580 }
1581 PaActivateAudioInterfaceCompletionHandler;
1582
1583 static HRESULT (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_QueryInterface)(
1584 IActivateAudioInterfaceCompletionHandler *This, REFIID riid, void **ppvObject)
1585 {
1586 PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
1587
1588 // From MSDN:
1589 // "The IAgileObject interface is a marker interface that indicates that an object
1590 // is free threaded and can be called from any apartment."
1591 if (IsEqualIID(riid, &IID_IUnknown) ||
1592 IsEqualIID(riid, &IID_IAgileObject))
1593 {
1594 IActivateAudioInterfaceCompletionHandler_AddRef((IActivateAudioInterfaceCompletionHandler *)handler);
1595 (*ppvObject) = handler;
1596 return S_OK;
1597 }
1598
1599 return E_NOINTERFACE;
1600 }
1601
1602 static ULONG (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_AddRef)(
1603 IActivateAudioInterfaceCompletionHandler *This)
1604 {
1605 PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
1606
1607 return InterlockedIncrement(&handler->refs);
1608 }
1609
1610 static ULONG (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_Release)(
1611 IActivateAudioInterfaceCompletionHandler *This)
1612 {
1613 PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
1614 ULONG refs;
1615
1616 if ((refs = InterlockedDecrement(&handler->refs)) == 0)
1617 {
1618 PaUtil_FreeMemory(handler->parent.lpVtbl);
1619 PaUtil_FreeMemory(handler);
1620 }
1621
1622 return refs;
1623 }
1624
1625 static HRESULT (STDMETHODCALLTYPE PaActivateAudioInterfaceCompletionHandler_ActivateCompleted)(
1626 IActivateAudioInterfaceCompletionHandler *This, IActivateAudioInterfaceAsyncOperation *activateOperation)
1627 {
1628 PaActivateAudioInterfaceCompletionHandler *handler = (PaActivateAudioInterfaceCompletionHandler *)This;
1629
1630 HRESULT hr = S_OK;
1631 HRESULT hrActivateResult = S_OK;
1632 IUnknown *punkAudioInterface = NULL;
1633
1634 // Check for a successful activation result
1635 hr = IActivateAudioInterfaceAsyncOperation_GetActivateResult(activateOperation, &hrActivateResult, &punkAudioInterface);
1636 if (SUCCEEDED(hr) && SUCCEEDED(hrActivateResult))
1637 {
1638 // Get pointer to the requested audio interface
1639 IUnknown_QueryInterface(punkAudioInterface, handler->in.iid, handler->in.obj);
1640 if ((*handler->in.obj) == NULL)
1641 hrActivateResult = E_FAIL;
1642 }
1643 SAFE_RELEASE(punkAudioInterface);
1644
1645 if (SUCCEEDED(hr))
1646 handler->out.hr = hrActivateResult;
1647 else
1648 handler->out.hr = hr;
1649
1650 // Got client object, stop busy waiting in ActivateAudioInterface
1651 InterlockedExchange(&handler->done, TRUE);
1652
1653 return hr;
1654 }
1655
1656 static IActivateAudioInterfaceCompletionHandler *CreateActivateAudioInterfaceCompletionHandler(const IID *iid, void **client)
1657 {
1658 PaActivateAudioInterfaceCompletionHandler *handler = PaUtil_AllocateMemory(sizeof(PaActivateAudioInterfaceCompletionHandler));
1659
1660 memset(handler, 0, sizeof(*handler));
1661
1662 handler->parent.lpVtbl = PaUtil_AllocateMemory(sizeof(*handler->parent.lpVtbl));
1663 handler->parent.lpVtbl->QueryInterface = &PaActivateAudioInterfaceCompletionHandler_QueryInterface;
1664 handler->parent.lpVtbl->AddRef = &PaActivateAudioInterfaceCompletionHandler_AddRef;
1665 handler->parent.lpVtbl->Release = &PaActivateAudioInterfaceCompletionHandler_Release;
1666 handler->parent.lpVtbl->ActivateCompleted = &PaActivateAudioInterfaceCompletionHandler_ActivateCompleted;
1667 handler->refs = 1;
1668 handler->in.iid = iid;
1669 handler->in.obj = client;
1670
1671 return (IActivateAudioInterfaceCompletionHandler *)handler;
1672 }
1673 #endif
1674
1675 // ------------------------------------------------------------------------------------------
1676 #ifdef PA_WINRT
1677 static HRESULT WinRT_GetDefaultDeviceId(WCHAR *deviceId, UINT32 deviceIdMax, EDataFlow flow)
1678 {
1679 switch (flow)
1680 {
1681 case eRender:
1682 if (g_DeviceListInfo.render.defaultId[0] != 0)
1683 wcsncpy_s(deviceId, deviceIdMax, g_DeviceListInfo.render.defaultId, wcslen(g_DeviceListInfo.render.defaultId));
1684 else
1685 StringFromGUID2(&DEVINTERFACE_AUDIO_RENDER, deviceId, deviceIdMax);
1686 break;
1687 case eCapture:
1688 if (g_DeviceListInfo.capture.defaultId[0] != 0)
1689 wcsncpy_s(deviceId, deviceIdMax, g_DeviceListInfo.capture.defaultId, wcslen(g_DeviceListInfo.capture.defaultId));
1690 else
1691 StringFromGUID2(&DEVINTERFACE_AUDIO_CAPTURE, deviceId, deviceIdMax);
1692 break;
1693 default:
1694 return S_FALSE;
1695 }
1696
1697 return S_OK;
1698 }
1699 #endif
1700
1701 // ------------------------------------------------------------------------------------------
1702 #ifdef PA_WINRT
1703 static HRESULT WinRT_ActivateAudioInterface(const WCHAR *deviceId, const IID *iid, void **client)
1704 {
1705 PaError result = paNoError;
1706 HRESULT hr = S_OK;
1707 IActivateAudioInterfaceAsyncOperation *asyncOp = NULL;
1708 IActivateAudioInterfaceCompletionHandler *handler = CreateActivateAudioInterfaceCompletionHandler(iid, client);
1709 PaActivateAudioInterfaceCompletionHandler *handlerImpl = (PaActivateAudioInterfaceCompletionHandler *)handler;
1710 UINT32 sleepToggle = 0;
1711
1712 // Async operation will call back to IActivateAudioInterfaceCompletionHandler::ActivateCompleted
1713 // which must be an agile interface implementation
1714 hr = ActivateAudioInterfaceAsync(deviceId, iid, NULL, handler, &asyncOp);
1715 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1716
1717 // Wait in busy loop for async operation to complete
1718 // Use Interlocked API here to ensure that ->done variable is read every time through the loop
1719 while (SUCCEEDED(hr) && !InterlockedOr(&handlerImpl->done, 0))
1720 {
1721 Sleep(sleepToggle ^= 1);
1722 }
1723
1724 hr = handlerImpl->out.hr;
1725
1726 error:
1727
1728 SAFE_RELEASE(asyncOp);
1729 SAFE_RELEASE(handler);
1730
1731 return hr;
1732 }
1733 #endif
1734
1735 // ------------------------------------------------------------------------------------------
1736 static HRESULT ActivateAudioInterface(const PaWasapiDeviceInfo *deviceInfo, const PaWasapiStreamInfo *streamInfo,
1737 IAudioClient **client)
1738 {
1739 HRESULT hr;
1740
1741 #ifndef PA_WINRT
1742 if (FAILED(hr = IMMDevice_Activate(deviceInfo->device, GetAudioClientIID(), CLSCTX_ALL, NULL, (void **)client)))
1743 return hr;
1744 #else
1745 if (FAILED(hr = WinRT_ActivateAudioInterface(deviceInfo->deviceId, GetAudioClientIID(), (void **)client)))
1746 return hr;
1747 #endif
1748
1749 // Set audio client options (applicable only to IAudioClient2+): options may affect the audio format
1750 // support by IAudioClient implementation and therefore we should set them before GetClosestFormat()
1751 // in order to correctly match the requested format
1752 #ifdef __IAudioClient2_INTERFACE_DEFINED__
1753 if ((streamInfo != NULL) && (GetAudioClientVersion() >= 2))
1754 {
1755 pa_AudioClientProperties audioProps = { 0 };
1756 audioProps.cbSize = sizeof(pa_AudioClientProperties);
1757 audioProps.bIsOffload = FALSE;
1758 audioProps.eCategory = (AUDIO_STREAM_CATEGORY)streamInfo->streamCategory;
1759 switch (streamInfo->streamOption)
1760 {
1761 case eStreamOptionRaw:
1762 if (GetWindowsVersion() >= WINDOWS_8_1_SERVER2012R2)
1763 audioProps.Options = pa_AUDCLNT_STREAMOPTIONS_RAW;
1764 break;
1765 case eStreamOptionMatchFormat:
1766 if (GetWindowsVersion() >= WINDOWS_10_SERVER2016)
1767 audioProps.Options = pa_AUDCLNT_STREAMOPTIONS_MATCH_FORMAT;
1768 break;
1769 }
1770
1771 if (FAILED(hr = IAudioClient2_SetClientProperties((IAudioClient2 *)(*client), (AudioClientProperties *)&audioProps)))
1772 {
1773 PRINT(("WASAPI: IAudioClient2_SetClientProperties(IsOffload = %d, Category = %d, Options = %d) failed\n", audioProps.bIsOffload, audioProps.eCategory, audioProps.Options));
1774 LogHostError(hr);
1775 }
1776 else
1777 {
1778 PRINT(("WASAPI: IAudioClient2 set properties: IsOffload = %d, Category = %d, Options = %d\n", audioProps.bIsOffload, audioProps.eCategory, audioProps.Options));
1779 }
1780 }
1781 #endif
1782
1783 return S_OK;
1784 }
1785
1786 // ------------------------------------------------------------------------------------------
1787 #ifdef PA_WINRT
1788 // Windows 10 SDK 10.0.15063.0 has SignalObjectAndWait defined again (unlike in 10.0.14393.0 and lower)
1789 #if !defined(WDK_NTDDI_VERSION) || (WDK_NTDDI_VERSION < NTDDI_WIN10_RS2)
1790 static DWORD SignalObjectAndWait(HANDLE hObjectToSignal, HANDLE hObjectToWaitOn, DWORD dwMilliseconds, BOOL bAlertable)
1791 {
1792 SetEvent(hObjectToSignal);
1793 return WaitForSingleObjectEx(hObjectToWaitOn, dwMilliseconds, bAlertable);
1794 }
1795 #endif
1796 #endif
1797
1798 // ------------------------------------------------------------------------------------------
1799 static void NotifyStateChanged(PaWasapiStream *stream, UINT32 flags, HRESULT hr)
1800 {
1801 if (stream->fnStateHandler == NULL)
1802 return;
1803
1804 if (FAILED(hr))
1805 flags |= paWasapiStreamStateError;
1806
1807 stream->fnStateHandler((PaStream *)stream, flags, hr, stream->pStateHandlerUserData);
1808 }
1809
1810 // ------------------------------------------------------------------------------------------
1811 static void FillBaseDeviceInfo(PaDeviceInfo *deviceInfo, PaHostApiIndex hostApiIndex)
1812 {
1813 deviceInfo->structVersion = 2;
1814 deviceInfo->hostApi = hostApiIndex;
1815 }
1816
1817 // ------------------------------------------------------------------------------------------
1818 static PaError FillInactiveDeviceInfo(PaWasapiHostApiRepresentation *paWasapi, PaDeviceInfo *deviceInfo)
1819 {
1820 if (deviceInfo->name == NULL)
1821 deviceInfo->name = (char *)PaUtil_GroupAllocateMemory(paWasapi->allocations, 1);
1822
1823 if (deviceInfo->name != NULL)
1824 {
1825 ((char *)deviceInfo->name)[0] = 0;
1826 }
1827 else
1828 return paInsufficientMemory;
1829
1830 return paNoError;
1831 }
1832
1833 // ------------------------------------------------------------------------------------------
1834 static PaError FillDeviceInfo(PaWasapiHostApiRepresentation *paWasapi, void *pEndPoints, INT32 index, const WCHAR *defaultRenderId,
1835 const WCHAR *defaultCaptureId, PaDeviceInfo *deviceInfo, PaWasapiDeviceInfo *wasapiDeviceInfo
1836 #ifdef PA_WINRT
1837 , PaWasapiWinrtDeviceListContext *deviceListContext
1838 #endif
1839 )
1840 {
1841 HRESULT hr;
1842 PaError result;
1843 PaUtilHostApiRepresentation *hostApi = (PaUtilHostApiRepresentation *)paWasapi;
1844 #ifdef PA_WINRT
1845 PaWasapiWinrtDeviceListContextEntry *listEntry = &deviceListContext->devices[index];
1846 (void)pEndPoints;
1847 (void)defaultRenderId;
1848 (void)defaultCaptureId;
1849 #endif
1850
1851 #ifndef PA_WINRT
1852 hr = IMMDeviceCollection_Item((IMMDeviceCollection *)pEndPoints, index, &wasapiDeviceInfo->device);
1853 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1854
1855 // Get device Id
1856 {
1857 WCHAR *deviceId;
1858
1859 hr = IMMDevice_GetId(wasapiDeviceInfo->device, &deviceId);
1860 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1861
1862 wcsncpy(wasapiDeviceInfo->deviceId, deviceId, PA_WASAPI_DEVICE_ID_LEN - 1);
1863 CoTaskMemFree(deviceId);
1864 }
1865
1866 // Get state of the device
1867 hr = IMMDevice_GetState(wasapiDeviceInfo->device, &wasapiDeviceInfo->state);
1868 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1869 if (wasapiDeviceInfo->state != DEVICE_STATE_ACTIVE)
1870 {
1871 PRINT(("WASAPI device: %d is not currently available (state:%d)\n", index, wasapiDeviceInfo->state));
1872 }
1873
1874 // Get basic device info
1875 {
1876 IPropertyStore *pProperty;
1877 IMMEndpoint *endpoint;
1878 PROPVARIANT value;
1879
1880 hr = IMMDevice_OpenPropertyStore(wasapiDeviceInfo->device, STGM_READ, &pProperty);
1881 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1882
1883 // "Friendly" Name
1884 {
1885 PropVariantInit(&value);
1886
1887 hr = IPropertyStore_GetValue(pProperty, &PKEY_Device_FriendlyName, &value);
1888 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1889
1890 if ((deviceInfo->name = (char *)PaUtil_GroupAllocateMemory(paWasapi->allocations, PA_WASAPI_DEVICE_NAME_LEN)) == NULL)
1891 {
1892 result = paInsufficientMemory;
1893 PropVariantClear(&value);
1894 goto error;
1895 }
1896 if (value.pwszVal)
1897 WideCharToMultiByte(CP_UTF8, 0, value.pwszVal, (INT32)wcslen(value.pwszVal), (char *)deviceInfo->name, PA_WASAPI_DEVICE_NAME_LEN - 1, 0, 0);
1898 else
1899 _snprintf((char *)deviceInfo->name, PA_WASAPI_DEVICE_NAME_LEN - 1, "baddev%d", index);
1900
1901 PropVariantClear(&value);
1902
1903 PA_DEBUG(("WASAPI:%d| name[%s]\n", index, deviceInfo->name));
1904 }
1905
1906 // Default format
1907 {
1908 PropVariantInit(&value);
1909
1910 hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEngine_DeviceFormat, &value);
1911 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1912
1913 memcpy(&wasapiDeviceInfo->DefaultFormat, value.blob.pBlobData, min(sizeof(wasapiDeviceInfo->DefaultFormat), value.blob.cbSize));
1914
1915 PropVariantClear(&value);
1916 }
1917
1918 // Form factor
1919 {
1920 PropVariantInit(&value);
1921
1922 hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEndpoint_FormFactor, &value);
1923 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1924
1925 // set
1926 #if defined(DUMMYUNIONNAME) && defined(NONAMELESSUNION)
1927 // avoid breaking strict-aliasing rules in such line: (EndpointFormFactor)(*((UINT *)(((WORD *)&value.wReserved3)+1)));
1928 UINT v;
1929 memcpy(&v, (((WORD *)&value.wReserved3) + 1), sizeof(v));
1930 wasapiDeviceInfo->formFactor = (EndpointFormFactor)v;
1931 #else
1932 wasapiDeviceInfo->formFactor = (EndpointFormFactor)value.uintVal;
1933 #endif
1934
1935 PA_DEBUG(("WASAPI:%d| form-factor[%d]\n", index, wasapiDeviceInfo->formFactor));
1936
1937 PropVariantClear(&value);
1938 }
1939
1940 // Data flow (Renderer or Capture)
1941 hr = IMMDevice_QueryInterface(wasapiDeviceInfo->device, &pa_IID_IMMEndpoint, (void **)&endpoint);
1942 if (SUCCEEDED(hr))
1943 {
1944 hr = IMMEndpoint_GetDataFlow(endpoint, &wasapiDeviceInfo->flow);
1945 SAFE_RELEASE(endpoint);
1946 }
1947
1948 SAFE_RELEASE(pProperty);
1949 }
1950 #else
1951 // Set device Id
1952 wcsncpy(wasapiDeviceInfo->deviceId, listEntry->info->id, PA_WASAPI_DEVICE_ID_LEN - 1);
1953
1954 // Set device name
1955 if ((deviceInfo->name = (char *)PaUtil_GroupAllocateMemory(paWasapi->allocations, PA_WASAPI_DEVICE_NAME_LEN)) == NULL)
1956 {
1957 result = paInsufficientMemory;
1958 goto error;
1959 }
1960 ((char *)deviceInfo->name)[0] = 0;
1961 if (listEntry->info->name[0] != 0)
1962 WideCharToMultiByte(CP_UTF8, 0, listEntry->info->name, (INT32)wcslen(listEntry->info->name), (char *)deviceInfo->name, PA_WASAPI_DEVICE_NAME_LEN - 1, 0, 0);
1963 if (deviceInfo->name[0] == 0) // fallback if WideCharToMultiByte is failed, or listEntry is nameless
1964 _snprintf((char *)deviceInfo->name, PA_WASAPI_DEVICE_NAME_LEN - 1, "WASAPI_%s:%d", (listEntry->flow == eRender ? "Output" : "Input"), index);
1965
1966 // Form-factor
1967 wasapiDeviceInfo->formFactor = listEntry->info->formFactor;
1968
1969 // Set data flow
1970 wasapiDeviceInfo->flow = listEntry->flow;
1971 #endif
1972
1973 // Set default Output/Input devices
1974 if ((defaultRenderId != NULL) && (wcsncmp(wasapiDeviceInfo->deviceId, defaultRenderId, PA_WASAPI_DEVICE_NAME_LEN - 1) == 0))
1975 hostApi->info.defaultOutputDevice = hostApi->info.deviceCount;
1976 if ((defaultCaptureId != NULL) && (wcsncmp(wasapiDeviceInfo->deviceId, defaultCaptureId, PA_WASAPI_DEVICE_NAME_LEN - 1) == 0))
1977 hostApi->info.defaultInputDevice = hostApi->info.deviceCount;
1978
1979 // Get a temporary IAudioClient for more details
1980 {
1981 IAudioClient *tmpClient;
1982 WAVEFORMATEX *mixFormat;
1983
1984 hr = ActivateAudioInterface(wasapiDeviceInfo, NULL, &tmpClient);
1985 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
1986
1987 // Get latency
1988 hr = IAudioClient_GetDevicePeriod(tmpClient, &wasapiDeviceInfo->DefaultDevicePeriod, &wasapiDeviceInfo->MinimumDevicePeriod);
1989 if (FAILED(hr))
1990 {
1991 PA_DEBUG(("WASAPI:%d| failed getting min/default periods by IAudioClient::GetDevicePeriod() with error[%08X], will use 30000/100000 hns\n", index, (UINT32)hr));
1992
1993 // assign WASAPI common values
1994 wasapiDeviceInfo->DefaultDevicePeriod = 100000;
1995 wasapiDeviceInfo->MinimumDevicePeriod = 30000;
1996
1997 // ignore error, let continue further without failing with paInternalError
1998 hr = S_OK;
1999 }
2000
2001 // Get mix format
2002 hr = IAudioClient_GetMixFormat(tmpClient, &mixFormat);
2003 if (SUCCEEDED(hr))
2004 {
2005 memcpy(&wasapiDeviceInfo->MixFormat, mixFormat, min(sizeof(wasapiDeviceInfo->MixFormat), (sizeof(*mixFormat) + mixFormat->cbSize)));
2006 CoTaskMemFree(mixFormat);
2007 }
2008
2009 // Register WINRT device
2010 #ifdef PA_WINRT
2011 if (SUCCEEDED(hr))
2012 {
2013 // Set state
2014 wasapiDeviceInfo->state = DEVICE_STATE_ACTIVE;
2015
2016 // Default format (Shared mode) is always a mix format
2017 wasapiDeviceInfo->DefaultFormat = wasapiDeviceInfo->MixFormat;
2018 }
2019 #endif
2020
2021 // Release tmp client
2022 SAFE_RELEASE(tmpClient);
2023
2024 if (hr != S_OK)
2025 {
2026 //davidv: this happened with my hardware, previously for that same device in DirectSound:
2027 //Digital Output (Realtek AC'97 Audio)'s GUID: {0x38f2cf50,0x7b4c,0x4740,0x86,0xeb,0xd4,0x38,0x66,0xd8,0xc8, 0x9f}
2028 //so something must be _really_ wrong with this device, TODO handle this better. We kind of need GetMixFormat
2029 LogHostError(hr);
2030 result = paInternalError;
2031 goto error;
2032 }
2033 }
2034
2035 // Fill basic device data
2036 deviceInfo->maxInputChannels = 0;
2037 deviceInfo->maxOutputChannels = 0;
2038 deviceInfo->defaultSampleRate = wasapiDeviceInfo->MixFormat.Format.nSamplesPerSec;
2039 switch (wasapiDeviceInfo->flow)
2040 {
2041 case eRender: {
2042 deviceInfo->maxOutputChannels = wasapiDeviceInfo->MixFormat.Format.nChannels;
2043 deviceInfo->defaultHighOutputLatency = nano100ToSeconds(wasapiDeviceInfo->DefaultDevicePeriod);
2044 deviceInfo->defaultLowOutputLatency = nano100ToSeconds(wasapiDeviceInfo->MinimumDevicePeriod);
2045 PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", index, (UINT32)deviceInfo->defaultSampleRate,
2046 deviceInfo->maxOutputChannels, (float)deviceInfo->defaultHighOutputLatency, (float)deviceInfo->defaultLowOutputLatency));
2047 break;}
2048 case eCapture: {
2049 deviceInfo->maxInputChannels = wasapiDeviceInfo->MixFormat.Format.nChannels;
2050 deviceInfo->defaultHighInputLatency = nano100ToSeconds(wasapiDeviceInfo->DefaultDevicePeriod);
2051 deviceInfo->defaultLowInputLatency = nano100ToSeconds(wasapiDeviceInfo->MinimumDevicePeriod);
2052 PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", index, (UINT32)deviceInfo->defaultSampleRate,
2053 deviceInfo->maxInputChannels, (float)deviceInfo->defaultHighInputLatency, (float)deviceInfo->defaultLowInputLatency));
2054 break; }
2055 default:
2056 PRINT(("WASAPI:%d| bad Data Flow!\n", index));
2057 result = paInternalError;
2058 goto error;
2059 }
2060
2061 return paNoError;
2062
2063 error:
2064
2065 PRINT(("WASAPI: failed filling device info for device index[%d] - error[%d|%s]\n", index, result, Pa_GetErrorText(result)));
2066
2067 return result;
2068 }
2069
2070 // ------------------------------------------------------------------------------------------
2071 static PaDeviceInfo *AllocateDeviceListMemory(PaWasapiHostApiRepresentation *paWasapi)
2072 {
2073 PaUtilHostApiRepresentation *hostApi = (PaUtilHostApiRepresentation *)paWasapi;
2074 PaDeviceInfo *deviceInfoArray = NULL;
2075
2076 if ((paWasapi->devInfo = (PaWasapiDeviceInfo *)PaUtil_GroupAllocateMemory(paWasapi->allocations,
2077 sizeof(PaWasapiDeviceInfo) * paWasapi->deviceCount)) == NULL)
2078 {
2079 return NULL;
2080 }
2081 memset(paWasapi->devInfo, 0, sizeof(PaWasapiDeviceInfo) * paWasapi->deviceCount);
2082
2083 if (paWasapi->deviceCount != 0)
2084 {
2085 UINT32 i;
2086 UINT32 deviceCount = paWasapi->deviceCount;
2087 #if defined(PA_WASAPI_MAX_CONST_DEVICE_COUNT) && (PA_WASAPI_MAX_CONST_DEVICE_COUNT > 0)
2088 if (deviceCount < PA_WASAPI_MAX_CONST_DEVICE_COUNT)
2089 deviceCount = PA_WASAPI_MAX_CONST_DEVICE_COUNT;
2090 #endif
2091
2092 if ((hostApi->deviceInfos = (PaDeviceInfo **)PaUtil_GroupAllocateMemory(paWasapi->allocations,
2093 sizeof(PaDeviceInfo *) * deviceCount)) == NULL)
2094 {
2095 return NULL;
2096 }
2097 for (i = 0; i < deviceCount; ++i)
2098 hostApi->deviceInfos[i] = NULL;
2099
2100 // Allocate all device info structs in a contiguous block
2101 if ((deviceInfoArray = (PaDeviceInfo *)PaUtil_GroupAllocateMemory(paWasapi->allocations,
2102 sizeof(PaDeviceInfo) * deviceCount)) == NULL)
2103 {
2104 return NULL;
2105 }
2106 memset(deviceInfoArray, 0, sizeof(PaDeviceInfo) * deviceCount);
2107 }
2108
2109 return deviceInfoArray;
2110 }
2111
2112 // ------------------------------------------------------------------------------------------
2113 static PaError CreateDeviceList(PaWasapiHostApiRepresentation *paWasapi, PaHostApiIndex hostApiIndex)
2114 {
2115 PaUtilHostApiRepresentation *hostApi = (PaUtilHostApiRepresentation *)paWasapi;
2116 PaError result = paNoError;
2117 PaDeviceInfo *deviceInfoArray = NULL;
2118 UINT32 i;
2119 WCHAR *defaultRenderId = NULL;
2120 WCHAR *defaultCaptureId = NULL;
2121 #ifndef PA_WINRT
2122 HRESULT hr;
2123 IMMDeviceCollection *pEndPoints = NULL;
2124 IMMDeviceEnumerator *pEnumerator = NULL;
2125 #else
2126 void *pEndPoints = NULL;
2127 IAudioClient *tmpClient;
2128 PaWasapiWinrtDeviceListContext deviceListContext = { 0 };
2129 PaWasapiWinrtDeviceInfo defaultRender = { 0 };
2130 PaWasapiWinrtDeviceInfo defaultCapture = { 0 };
2131 #endif
2132
2133 // Make sure device list empty
2134 if ((paWasapi->deviceCount != 0) || (hostApi->info.deviceCount != 0))
2135 return paInternalError;
2136
2137 #ifndef PA_WINRT
2138 hr = CoCreateInstance(&pa_CLSID_IMMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER,
2139 &pa_IID_IMMDeviceEnumerator, (void **)&pEnumerator);
2140 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
2141
2142 // Get default render and capture devices
2143 {
2144 IMMDevice *device;
2145
2146 hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(pEnumerator, eRender, eMultimedia, &device);
2147 if (hr != S_OK)
2148 {
2149 if (hr != E_NOTFOUND)
2150 {
2151 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
2152 }
2153 }
2154 else
2155 {
2156 hr = IMMDevice_GetId(device, &defaultRenderId);
2157 IMMDevice_Release(device);
2158 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
2159 }
2160
2161 hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(pEnumerator, eCapture, eMultimedia, &device);
2162 if (hr != S_OK)
2163 {
2164 if (hr != E_NOTFOUND)
2165 {
2166 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
2167 }
2168 }
2169 else
2170 {
2171 hr = IMMDevice_GetId(device, &defaultCaptureId);
2172 IMMDevice_Release(device);
2173 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
2174 }
2175 }
2176
2177 // Get all currently active devices
2178 hr = IMMDeviceEnumerator_EnumAudioEndpoints(pEnumerator, eAll, DEVICE_STATE_ACTIVE, &pEndPoints);
2179 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
2180
2181 // Get device count
2182 hr = IMMDeviceCollection_GetCount(pEndPoints, &paWasapi->deviceCount);
2183 IF_FAILED_INTERNAL_ERROR_JUMP(hr, result, error);
2184 #else
2185 WinRT_GetDefaultDeviceId(defaultRender.id, STATIC_ARRAY_SIZE(defaultRender.id) - 1, eRender);
2186 defaultRenderId = defaultRender.id;
2187
2188 WinRT_GetDefaultDeviceId(defaultCapture.id, STATIC_ARRAY_SIZE(defaultCapture.id) - 1, eCapture);
2189 defaultCaptureId = defaultCapture.id;
2190
2191 if (g_DeviceListInfo.render.deviceCount == 0)
2192 {
2193 if (SUCCEEDED(WinRT_ActivateAudioInterface(defaultRenderId, GetAudioClientIID(), &tmpClient)))
2194 {
2195 deviceListContext.devices[paWasapi->deviceCount].info = &defaultRender;
2196 deviceListContext.devices[paWasapi->deviceCount].flow = eRender;
2197 paWasapi->deviceCount++;
2198
2199 SAFE_RELEASE(tmpClient);
2200 }
2201 }
2202 else
2203 {
2204 for (i = 0; i < g_DeviceListInfo.render.deviceCount; ++i)
2205 {
2206 deviceListContext.devices[paWasapi->deviceCount].info = &g_DeviceListInfo.render.devices[i];
2207 deviceListContext.devices[paWasapi->deviceCount].flow = eRender;
2208 paWasapi->deviceCount++;
2209 }
2210 }
2211
2212 if (g_DeviceListInfo.capture.deviceCount == 0)
2213 {
2214 if (SUCCEEDED(WinRT_ActivateAudioInterface(defaultCaptureId, GetAudioClientIID(), &tmpClient)))
2215 {
2216 deviceListContext.devices[paWasapi->deviceCount].info = &defaultCapture;
2217 deviceListContext.devices[paWasapi->deviceCount].flow = eCapture;
2218 paWasapi->deviceCount++;
2219
2220 SAFE_RELEASE(tmpClient);
2221 }
2222 }
2223 else
2224 {
2225 for (i = 0; i < g_DeviceListInfo.capture.deviceCount; ++i)
2226 {
2227 deviceListContext.devices[paWasapi->deviceCount].info = &g_DeviceListInfo.capture.devices[i];
2228 deviceListContext.devices[paWasapi->deviceCount].flow = eCapture;
2229 paWasapi->deviceCount++;
2230 }
2231 }
2232 #endif
2233
2234 // Allocate memory for the device list
2235 if ((paWasapi->deviceCount != 0) && ((deviceInfoArray = AllocateDeviceListMemory(paWasapi)) == NULL))
2236 {
2237 result = paInsufficientMemory;
2238 goto error;
2239 }
2240
2241 // Fill WASAPI device info
2242 for (i = 0; i < paWasapi->deviceCount; ++i)
2243 {
2244 PaDeviceInfo *deviceInfo = &deviceInfoArray[i];
2245
2246 PA_DEBUG(("WASAPI: device idx: %02d\n", i));
2247 PA_DEBUG(("WASAPI: ---------------\n"));
2248
2249 FillBaseDeviceInfo(deviceInfo, hostApiIndex);
2250
2251 if ((result = FillDeviceInfo(paWasapi, pEndPoints, i, defaultRenderId, defaultCaptureId,
2252 deviceInfo, &paWasapi->devInfo[i]
2253 #ifdef PA_WINRT
2254 , &deviceListContext
2255 #endif
2256 )) != paNoError)
2257 {
2258 // Faulty device is made inactive
2259 if ((result = FillInactiveDeviceInfo(paWasapi, deviceInfo)) != paNoError)
2260 goto error;
2261 }
2262
2263 hostApi->deviceInfos[i] = deviceInfo;
2264 ++hostApi->info.deviceCount;
2265 }
2266
2267 // Fill the remaining slots with inactive device info
2268 #if defined(PA_WASAPI_MAX_CONST_DEVICE_COUNT) && (PA_WASAPI_MAX_CONST_DEVICE_COUNT > 0)
2269 if ((hostApi->info.deviceCount != 0) && (hostApi->info.deviceCount < PA_WASAPI_MAX_CONST_DEVICE_COUNT))
2270 {
2271 for (i = hostApi->info.deviceCount; i < PA_WASAPI_MAX_CONST_DEVICE_COUNT; ++i)
2272 {
2273 PaDeviceInfo *deviceInfo = &deviceInfoArray[i];
2274
2275 FillBaseDeviceInfo(deviceInfo, hostApiIndex);
2276
2277 if ((result = FillInactiveDeviceInfo(paWasapi, deviceInfo)) != paNoError)
2278 goto error;
2279
2280 hostApi->deviceInfos[i] = deviceInfo;
2281 ++hostApi->info.deviceCount;
2282 }
2283 }
2284 #endif
2285
2286 // Clear any non-fatal errors
2287 result = paNoError;
2288
2289 PRINT(("WASAPI: device list ok - found %d devices\n", paWasapi->deviceCount));
2290
2291 done:
2292
2293 #ifndef PA_WINRT
2294 CoTaskMemFree(defaultRenderId);
2295 CoTaskMemFree(defaultCaptureId);
2296 SAFE_RELEASE(pEndPoints);
2297 SAFE_RELEASE(pEnumerator);
2298 #endif
2299
2300 return result;
2301
2302 error:
2303
2304 // Safety if error was not set so that we do not think initialize was a success
2305 if (result == paNoError)
2306 result = paInternalError;
2307
2308 PRINT(("WASAPI: failed to create device list - error[%d|%s]\n", result, Pa_GetErrorText(result)));
2309
2310 goto done;
2311 }
2312
2313 // ------------------------------------------------------------------------------------------
2314 PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
2315 {
2316 PaError result;
2317 PaWasapiHostApiRepresentation *paWasapi;
2318
2319 #ifndef PA_WINRT
2320 if (!SetupAVRT())
2321 {
2322 PRINT(("WASAPI: No AVRT! (not VISTA?)\n"));
2323 return paNoError;
2324 }
2325 #endif
2326
2327 paWasapi = (PaWasapiHostApiRepresentation *)PaUtil_AllocateMemory(sizeof(PaWasapiHostApiRepresentation));
2328 if (paWasapi == NULL)
2329 {
2330 result = paInsufficientMemory;
2331 goto error;
2332 }
2333 memset(paWasapi, 0, sizeof(PaWasapiHostApiRepresentation)); /* ensure all fields are zeroed. especially paWasapi->allocations */
2334
2335 // Initialize COM subsystem
2336 result = PaWinUtil_CoInitialize(paWASAPI, &paWasapi->comInitializationResult);
2337 if (result != paNoError)
2338 goto error;
2339
2340 // Create memory group
2341 paWasapi->allocations = PaUtil_CreateAllocationGroup();
2342 if (paWasapi->allocations == NULL)
2343 {
2344 result = paInsufficientMemory;
2345 goto error;
2346 }
2347
2348 // Fill basic interface info
2349 *hostApi = &paWasapi->inheritedHostApiRep;
2350 (*hostApi)->info.structVersion = 1;
2351 (*hostApi)->info.type = paWASAPI;
2352 (*hostApi)->info.name = "Windows WASAPI";
2353 (*hostApi)->info.deviceCount = 0;
2354 (*hostApi)->info.defaultInputDevice = paNoDevice;
2355 (*hostApi)->info.defaultOutputDevice = paNoDevice;
2356 (*hostApi)->Terminate = Terminate;
2357 (*hostApi)->OpenStream = OpenStream;
2358 (*hostApi)->IsFormatSupported = IsFormatSupported;
2359
2360 // Fill the device list
2361 if ((result = CreateDeviceList(paWasapi, hostApiIndex)) != paNoError)
2362 goto error;
2363
2364 // Detect if platform workaround is required
2365 paWasapi->useWOW64Workaround = UseWOW64Workaround();
2366
2367 // Initialize time getter
2368 SystemTimer_InitializeTimeGetter();
2369
2370 PaUtil_InitializeStreamInterface( &paWasapi->callbackStreamInterface, CloseStream, StartStream,
2371 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
2372 GetStreamTime, GetStreamCpuLoad,
2373 PaUtil_DummyRead, PaUtil_DummyWrite,
2374 PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
2375
2376 PaUtil_InitializeStreamInterface( &paWasapi->blockingStreamInterface, CloseStream, StartStream,
2377 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
2378 GetStreamTime, PaUtil_DummyGetCpuLoad,
2379 ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
2380
2381 PRINT(("WASAPI: initialized ok\n"));
2382
2383 return paNoError;
2384
2385 error:
2386
2387 PRINT(("WASAPI: failed %s error[%d|%s]\n", __FUNCTION__, result, Pa_GetErrorText(result)));
2388
2389 Terminate((PaUtilHostApiRepresentation *)paWasapi);
2390
2391 return result;
2392 }
2393
2394 // ------------------------------------------------------------------------------------------
2395 static void ReleaseWasapiDeviceInfoList( PaWasapiHostApiRepresentation *paWasapi )
2396 {
2397 UINT32 i;
2398
2399 // Release device info bound objects
2400 for (i = 0; i < paWasapi->deviceCount; ++i)
2401 {
2402 #ifndef PA_WINRT
2403 SAFE_RELEASE(paWasapi->devInfo[i].device);
2404 #endif
2405 }
2406
2407 // Free device info
2408 if (paWasapi->allocations != NULL)
2409 PaUtil_GroupFreeMemory(paWasapi->allocations, paWasapi->devInfo);
2410
2411 // Be ready for a device list reinitialization and if its creation is failed pointers must not be dangling
2412 paWasapi->devInfo = NULL;
2413 paWasapi->deviceCount = 0;
2414 }
2415
2416 // ------------------------------------------------------------------------------------------
2417 static void Terminate( PaUtilHostApiRepresentation *hostApi )
2418 {
2419 PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
2420 if (paWasapi == NULL)
2421 return;
2422
2423 // Release device list
2424 ReleaseWasapiDeviceInfoList(paWasapi);
2425
2426 // Free allocations and memory group itself
2427 if (paWasapi->allocations != NULL)
2428 {
2429 PaUtil_FreeAllAllocations(paWasapi->allocations);
2430 PaUtil_DestroyAllocationGroup(paWasapi->allocations);
2431 }
2432
2433 // Release COM subsystem
2434 PaWinUtil_CoUninitialize(paWASAPI, &paWasapi->comInitializationResult);
2435
2436 // Free API representation
2437 PaUtil_FreeMemory(paWasapi);
2438
2439 // Close AVRT
2440 CloseAVRT();
2441 }
2442
2443 // ------------------------------------------------------------------------------------------
2444 static PaWasapiHostApiRepresentation *_GetHostApi(PaError *ret)
2445 {
2446 PaError error;
2447 PaUtilHostApiRepresentation *pApi;
2448
2449 if ((error = PaUtil_GetHostApiRepresentation(&pApi, paWASAPI)) != paNoError)
2450 {
2451 if (ret != NULL)
2452 (*ret) = error;
2453
2454 return NULL;
2455 }
2456
2457 return (PaWasapiHostApiRepresentation *)pApi;
2458 }
2459
2460 // ------------------------------------------------------------------------------------------
2461 static PaError UpdateDeviceList()
2462 {
2463 int i;
2464 PaError ret;
2465 PaWasapiHostApiRepresentation *paWasapi;
2466 PaUtilHostApiRepresentation *hostApi;
2467
2468 // Get API
2469 hostApi = (PaUtilHostApiRepresentation *)(paWasapi = _GetHostApi(&ret));
2470 if (paWasapi == NULL)
2471 return paNotInitialized;
2472
2473 // Make sure initialized properly
2474 if (paWasapi->allocations == NULL)
2475 return paNotInitialized;
2476
2477 // Release WASAPI internal device info list
2478 ReleaseWasapiDeviceInfoList(paWasapi);
2479
2480 // Release external device info list
2481 if (hostApi->deviceInfos != NULL)
2482 {
2483 for (i = 0; i < hostApi->info.deviceCount; ++i)
2484 {
2485 PaUtil_GroupFreeMemory(paWasapi->allocations, (void *)hostApi->deviceInfos[i]->name);
2486 }
2487 PaUtil_GroupFreeMemory(paWasapi->allocations, hostApi->deviceInfos[0]);
2488 PaUtil_GroupFreeMemory(paWasapi->allocations, hostApi->deviceInfos);
2489
2490 // Be ready for a device list reinitialization and if its creation is failed pointers must not be dangling
2491 hostApi->deviceInfos = NULL;
2492 hostApi->info.deviceCount = 0;
2493 hostApi->info.defaultInputDevice = paNoDevice;
2494 hostApi->info.defaultOutputDevice = paNoDevice;
2495 }
2496
2497 // Fill possibly updated device list
2498 if ((ret = CreateDeviceList(paWasapi, Pa_HostApiTypeIdToHostApiIndex(paWASAPI))) != paNoError)
2499 return ret;
2500
2501 return paNoError;
2502 }
2503
2504 // ------------------------------------------------------------------------------------------
2505 PaError PaWasapi_UpdateDeviceList()
2506 {
2507 #if defined(PA_WASAPI_MAX_CONST_DEVICE_COUNT) && (PA_WASAPI_MAX_CONST_DEVICE_COUNT > 0)
2508 return UpdateDeviceList();
2509 #else
2510 return paInternalError;
2511 #endif
2512 }
2513
2514 // ------------------------------------------------------------------------------------------
2515 int PaWasapi_GetDeviceCurrentFormat( PaStream *pStream, void *pFormat, unsigned int formatSize, int bOutput )
2516 {
2517 UINT32 size;
2518 WAVEFORMATEXTENSIBLE *format;
2519
2520 PaWasapiStream *stream = (PaWasapiStream *)pStream;
2521 if (stream == NULL)
2522 return paBadStreamPtr;
2523
2524 format = (bOutput == TRUE ? &stream->out.wavex : &stream->in.wavex);
2525
2526 size = min(formatSize, (UINT32)sizeof(*format));
2527 memcpy(pFormat, format, size);
2528
2529 return size;
2530 }
2531
2532 // ------------------------------------------------------------------------------------------
2533 static PaError _GetWasapiDeviceInfoByDeviceIndex( PaWasapiDeviceInfo **info, PaDeviceIndex device )
2534 {
2535 PaError ret;
2536 PaDeviceIndex index;
2537
2538 // Get API
2539 PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
2540 if (paWasapi == NULL)
2541 return paNotInitialized;
2542
2543 // Get device index
2544 if ((ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, device, &paWasapi->inheritedHostApiRep)) != paNoError)
2545 return ret;
2546
2547 // Validate index
2548 if ((UINT32)index >= paWasapi->deviceCount)
2549 return paInvalidDevice;
2550
2551 (*info) = &paWasapi->devInfo[ index ];
2552
2553 return paNoError;
2554 }
2555
2556 // ------------------------------------------------------------------------------------------
2557 int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int formatSize, PaDeviceIndex device )
2558 {
2559 PaError ret;
2560 PaWasapiDeviceInfo *deviceInfo;
2561 UINT32 size;
2562
2563 if (pFormat == NULL)
2564 return paBadBufferPtr;
2565 if (formatSize <= 0)
2566 return paBufferTooSmall;
2567
2568 if ((ret = _GetWasapiDeviceInfoByDeviceIndex(&deviceInfo, device)) != paNoError)
2569 return ret;
2570
2571 size = min(formatSize, (UINT32)sizeof(deviceInfo->DefaultFormat));
2572 memcpy(pFormat, &deviceInfo->DefaultFormat, size);
2573
2574 return size;
2575 }
2576
2577 // ------------------------------------------------------------------------------------------
2578 int PaWasapi_GetDeviceMixFormat( void *pFormat, unsigned int formatSize, PaDeviceIndex device )
2579 {
2580 PaError ret;
2581 PaWasapiDeviceInfo *deviceInfo;
2582 UINT32 size;
2583
2584 if (pFormat == NULL)
2585 return paBadBufferPtr;
2586 if (formatSize <= 0)
2587 return paBufferTooSmall;
2588
2589 if ((ret = _GetWasapiDeviceInfoByDeviceIndex(&deviceInfo, device)) != paNoError)
2590 return ret;
2591
2592 size = min(formatSize, (UINT32)sizeof(deviceInfo->MixFormat));
2593 memcpy(pFormat, &deviceInfo->MixFormat, size);
2594
2595 return size;
2596 }
2597
2598 // ------------------------------------------------------------------------------------------
2599 int PaWasapi_GetDeviceRole( PaDeviceIndex device )
2600 {
2601 PaError ret;
2602 PaWasapiDeviceInfo *deviceInfo;
2603
2604 if ((ret = _GetWasapiDeviceInfoByDeviceIndex(&deviceInfo, device)) != paNoError)
2605 return ret;
2606
2607 return deviceInfo->formFactor;
2608 }
2609
2610 // ------------------------------------------------------------------------------------------
2611 PaError PaWasapi_GetIMMDevice( PaDeviceIndex device, void **pIMMDevice )
2612 {
2613 #ifndef PA_WINRT
2614 PaError ret;
2615 PaWasapiDeviceInfo *deviceInfo;
2616
2617 if (pIMMDevice == NULL)
2618 return paBadBufferPtr;
2619
2620 if ((ret = _GetWasapiDeviceInfoByDeviceIndex(&deviceInfo, device)) != paNoError)
2621 return ret;
2622
2623 (*pIMMDevice) = deviceInfo->device;
2624
2625 return paNoError;
2626 #else
2627 (void)device;
2628 (void)pIMMDevice;
2629 return paIncompatibleStreamHostApi;
2630 #endif
2631 }
2632
2633 // ------------------------------------------------------------------------------------------
2634 PaError PaWasapi_GetFramesPerHostBuffer( PaStream *pStream, unsigned int *pInput, unsigned int *pOutput )
2635 {
2636 PaWasapiStream *stream = (PaWasapiStream *)pStream;
2637 if (stream == NULL)
2638 return paBadStreamPtr;
2639
2640 if (pInput != NULL)
2641 (*pInput) = stream->in.framesPerHostCallback;
2642
2643 if (pOutput != NULL)
2644 (*pOutput) = stream->out.framesPerHostCallback;
2645
2646 return paNoError;
2647 }
2648
2649 // ------------------------------------------------------------------------------------------
2650 static void LogWAVEFORMATEXTENSIBLE(const WAVEFORMATEXTENSIBLE *in)
2651 {
2652 const WAVEFORMATEX *old = (WAVEFORMATEX *)in;
2653 switch (old->wFormatTag)
2654 {
2655 case WAVE_FORMAT_EXTENSIBLE: {
2656
2657 PRINT(("wFormatTag =WAVE_FORMAT_EXTENSIBLE\n"));
2658
2659 if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
2660 {
2661 PRINT(("SubFormat =KSDATAFORMAT_SUBTYPE_IEEE_FLOAT\n"));
2662 }
2663 else
2664 if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
2665 {
2666 PRINT(("SubFormat =KSDATAFORMAT_SUBTYPE_PCM\n"));
2667 }
2668 else
2669 {
2670 PRINT(("SubFormat =CUSTOM GUID{%d:%d:%d:%d%d%d%d%d%d%d%d}\n",
2671 in->SubFormat.Data1,
2672 in->SubFormat.Data2,
2673 in->SubFormat.Data3,
2674 (int)in->SubFormat.Data4[0],
2675 (int)in->SubFormat.Data4[1],
2676 (int)in->SubFormat.Data4[2],
2677 (int)in->SubFormat.Data4[3],
2678 (int)in->SubFormat.Data4[4],
2679 (int)in->SubFormat.Data4[5],
2680 (int)in->SubFormat.Data4[6],
2681 (int)in->SubFormat.Data4[7]));
2682 }
2683 PRINT(("Samples.wValidBitsPerSample =%d\n", in->Samples.wValidBitsPerSample));
2684 PRINT(("dwChannelMask =0x%X\n",in->dwChannelMask));
2685
2686 break; }
2687
2688 case WAVE_FORMAT_PCM: PRINT(("wFormatTag =WAVE_FORMAT_PCM\n")); break;
2689 case WAVE_FORMAT_IEEE_FLOAT: PRINT(("wFormatTag =WAVE_FORMAT_IEEE_FLOAT\n")); break;
2690 default:
2691 PRINT(("wFormatTag =UNKNOWN(%d)\n",old->wFormatTag)); break;
2692 }
2693
2694 PRINT(("nChannels =%d\n",old->nChannels));
2695 PRINT(("nSamplesPerSec =%d\n",old->nSamplesPerSec));
2696 PRINT(("nAvgBytesPerSec=%d\n",old->nAvgBytesPerSec));
2697 PRINT(("nBlockAlign =%d\n",old->nBlockAlign));
2698 PRINT(("wBitsPerSample =%d\n",old->wBitsPerSample));
2699 PRINT(("cbSize =%d\n",old->cbSize));
2700 }
2701
2702 // ------------------------------------------------------------------------------------------
2703 PaSampleFormat WaveToPaFormat(const WAVEFORMATEXTENSIBLE *fmtext)
2704 {
2705 const WAVEFORMATEX *fmt = (WAVEFORMATEX *)fmtext;
2706
2707 switch (fmt->wFormatTag)
2708 {
2709 case WAVE_FORMAT_EXTENSIBLE: {
2710 if (IsEqualGUID(&fmtext->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
2711 {
2712 if (fmtext->Samples.wValidBitsPerSample == 32)
2713 return paFloat32;
2714 }
2715 else
2716 if (IsEqualGUID(&fmtext->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
2717 {
2718 switch (fmt->wBitsPerSample)
2719 {
2720 case 32: return paInt32;
2721 case 24: return paInt24;
2722 case 16: return paInt16;
2723 case 8: return paUInt8;
2724 }
2725 }
2726 break; }
2727
2728 case WAVE_FORMAT_IEEE_FLOAT:
2729 return paFloat32;
2730
2731 case WAVE_FORMAT_PCM: {
2732 switch (fmt->wBitsPerSample)
2733 {
2734 case 32: return paInt32;
2735 case 24: return paInt24;
2736 case 16: return paInt16;
2737 case 8: return paUInt8;
2738 }
2739 break; }
2740 }
2741
2742 return paCustomFormat;
2743 }
2744
2745 // ------------------------------------------------------------------------------------------
2746 static PaError MakeWaveFormatFromParams(WAVEFORMATEXTENSIBLE *wavex, const PaStreamParameters *params,
2747 double sampleRate, BOOL packedOnly)
2748 {
2749 WORD bitsPerSample;
2750 WAVEFORMATEX *old;
2751 DWORD channelMask = 0;
2752 BOOL useExtensible = (params->channelCount > 2); // format is always forced for >2 channels format
2753 PaWasapiStreamInfo *streamInfo = (PaWasapiStreamInfo *)params->hostApiSpecificStreamInfo;
2754
2755 // Convert PaSampleFormat to valid data bits
2756 if ((bitsPerSample = PaSampleFormatToBitsPerSample(params->sampleFormat)) == 0)
2757 return paSampleFormatNotSupported;
2758
2759 // Use user assigned channel mask
2760 if ((streamInfo != NULL) && (streamInfo->flags & paWinWasapiUseChannelMask))
2761 {
2762 channelMask = streamInfo->channelMask;
2763 useExtensible = TRUE;
2764 }
2765
2766 memset(wavex, 0, sizeof(*wavex));
2767
2768 old = (WAVEFORMATEX *)wavex;
2769 old->nChannels = (WORD)params->channelCount;
2770 old->nSamplesPerSec = (DWORD)sampleRate;
2771 old->wBitsPerSample = bitsPerSample;
2772
2773 // according to MSDN for WAVEFORMATEX structure for WAVE_FORMAT_PCM:
2774 // "If wFormatTag is WAVE_FORMAT_PCM, then wBitsPerSample should be equal to 8 or 16."
2775 if ((bitsPerSample != 8) && (bitsPerSample != 16))
2776 {
2777 // Normally 20 or 24 bits must go in 32 bit containers (ints) but in Exclusive mode some devices require
2778 // packed version of the format, e.g. for example 24-bit in 3-bytes
2779 old->wBitsPerSample = (packedOnly ? bitsPerSample : 32);
2780 useExtensible = TRUE;
2781 }
2782
2783 // WAVEFORMATEX
2784 if (!useExtensible)
2785 {
2786 old->wFormatTag = WAVE_FORMAT_PCM;
2787 }
2788 // WAVEFORMATEXTENSIBLE
2789 else
2790 {
2791 old->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
2792 old->cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
2793
2794 if ((params->sampleFormat & ~paNonInterleaved) == paFloat32)
2795 wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
2796 else
2797 wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
2798
2799 wavex->Samples.wValidBitsPerSample = bitsPerSample;
2800
2801 // Set channel mask
2802 if (channelMask != 0)
2803 {
2804 wavex->dwChannelMask = channelMask;
2805 }
2806 else
2807 {
2808 switch (params->channelCount)
2809 {
2810 case 1: wavex->dwChannelMask = PAWIN_SPEAKER_MONO; break;
2811 case 2: wavex->dwChannelMask = PAWIN_SPEAKER_STEREO; break;
2812 case 3: wavex->dwChannelMask = PAWIN_SPEAKER_STEREO|SPEAKER_LOW_FREQUENCY; break;
2813 case 4: wavex->dwChannelMask = PAWIN_SPEAKER_QUAD; break;
2814 case 5: wavex->dwChannelMask = PAWIN_SPEAKER_QUAD|SPEAKER_LOW_FREQUENCY; break;
2815 #ifdef PAWIN_SPEAKER_5POINT1_SURROUND
2816 case 6: wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1_SURROUND; break;
2817 #else
2818 case 6: wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1; break;
2819 #endif
2820 #ifdef PAWIN_SPEAKER_5POINT1_SURROUND
2821 case 7: wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1_SURROUND|SPEAKER_BACK_CENTER; break;
2822 #else
2823 case 7: wavex->dwChannelMask = PAWIN_SPEAKER_5POINT1|SPEAKER_BACK_CENTER; break;
2824 #endif
2825 #ifdef PAWIN_SPEAKER_7POINT1_SURROUND
2826 case 8: wavex->dwChannelMask = PAWIN_SPEAKER_7POINT1_SURROUND; break;
2827 #else
2828 case 8: wavex->dwChannelMask = PAWIN_SPEAKER_7POINT1; break;
2829 #endif
2830
2831 default: wavex->dwChannelMask = 0;
2832 }
2833 }
2834 }
2835
2836 old->nBlockAlign = old->nChannels * (old->wBitsPerSample / 8);
2837 old->nAvgBytesPerSec = old->nSamplesPerSec * old->nBlockAlign;
2838
2839 return paNoError;
2840 }
2841
2842 // ------------------------------------------------------------------------------------------
2843 static HRESULT GetAlternativeSampleFormatExclusive(IAudioClient *client, double sampleRate,
2844 const PaStreamParameters *params, WAVEFORMATEXTENSIBLE *outWavex, BOOL packedSampleFormatOnly)
2845 {
2846 HRESULT hr = !S_OK;
2847 AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
2848 WAVEFORMATEXTENSIBLE testFormat;
2849 PaStreamParameters testParams;
2850 int i;
2851 static const PaSampleFormat bestToWorst[] = { paInt32, paInt24, paFloat32, paInt16 };
2852
2853 // Try combination Stereo (2 channels) and then we will use our custom mono-stereo mixer
2854 if (params->channelCount == 1)
2855 {
2856 testParams = (*params);
2857 testParams.channelCount = 2;
2858
2859 if (MakeWaveFormatFromParams(&testFormat, &testParams, sampleRate, packedSampleFormatOnly) == paNoError)
2860 {
2861 if ((hr = IAudioClient_IsFormatSupported(client, shareMode, &testFormat.Format, NULL)) == S_OK)
2862 {
2863 (*outWavex) = testFormat;
2864 return hr;
2865 }
2866 }
2867
2868 // Try selecting suitable sample type
2869 for (i = 0; i < STATIC_ARRAY_SIZE(bestToWorst); ++i)
2870 {
2871 testParams.sampleFormat = bestToWorst[i];
2872
2873 if (MakeWaveFormatFromParams(&testFormat, &testParams, sampleRate, packedSampleFormatOnly) == paNoError)
2874 {
2875 if ((hr = IAudioClient_IsFormatSupported(client, shareMode, &testFormat.Format, NULL)) == S_OK)
2876 {
2877 (*outWavex) = testFormat;
2878 return hr;
2879 }
2880 }
2881 }
2882 }
2883
2884 // Try selecting suitable sample type
2885 testParams = (*params);
2886 for (i = 0; i < STATIC_ARRAY_SIZE(bestToWorst); ++i)
2887 {
2888 testParams.sampleFormat = bestToWorst[i];
2889
2890 if (MakeWaveFormatFromParams(&testFormat, &testParams, sampleRate, packedSampleFormatOnly) == paNoError)
2891 {
2892 if ((hr = IAudioClient_IsFormatSupported(client, shareMode, &testFormat.Format, NULL)) == S_OK)
2893 {
2894 (*outWavex) = testFormat;
2895 return hr;
2896 }
2897 }
2898 }
2899
2900 return hr;
2901 }
2902
2903 // ------------------------------------------------------------------------------------------
2904 static PaError GetClosestFormat(IAudioClient *client, double sampleRate, const PaStreamParameters *_params,
2905 AUDCLNT_SHAREMODE shareMode, WAVEFORMATEXTENSIBLE *outWavex, BOOL output)
2906 {
2907 PaWasapiStreamInfo *streamInfo = (PaWasapiStreamInfo *)_params->hostApiSpecificStreamInfo;
2908 WAVEFORMATEX *sharedClosestMatch = NULL;
2909 HRESULT hr = !S_OK;
2910 PaStreamParameters params = (*_params);
2911 const BOOL explicitFormat = (streamInfo != NULL) && ((streamInfo->flags & paWinWasapiExplicitSampleFormat) == paWinWasapiExplicitSampleFormat);
2912 (void)output;
2913
2914 /* It was not noticed that 24-bit Input producing no output while device accepts this format.
2915 To fix this issue let's ask for 32-bits and let PA converters convert host 32-bit data
2916 to 24-bit for user-space. The bug concerns Vista, if Windows 7 supports 24-bits for Input
2917 please report to PortAudio developers to exclude Windows 7.
2918 */
2919 /*if ((params.sampleFormat == paInt24) && (output == FALSE))
2920 params.sampleFormat = paFloat32;*/ // <<< The silence was due to missing Int32_To_Int24_Dither implementation
2921
2922 // Try standard approach, e.g. if data is > 16 bits it will be packed into 32-bit containers
2923 MakeWaveFormatFromParams(outWavex, &params, sampleRate, FALSE);
2924
2925 // If built-in PCM converter requested then shared mode format will always succeed
2926 if ((GetWindowsVersion() >= WINDOWS_7_SERVER2008R2) &&
2927 (shareMode == AUDCLNT_SHAREMODE_SHARED) &&
2928 ((streamInfo != NULL) && (streamInfo->flags & paWinWasapiAutoConvert)))
2929 return paFormatIsSupported;
2930
2931 hr = IAudioClient_IsFormatSupported(client, shareMode, &outWavex->Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
2932
2933 // Exclusive mode can require packed format for some devices
2934 if ((hr != S_OK) && (shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE))
2935 {
2936 // Enforce packed only format, e.g. data bits will not be packed into 32-bit containers in any case
2937 MakeWaveFormatFromParams(outWavex, &params, sampleRate, TRUE);
2938 hr = IAudioClient_IsFormatSupported(client, shareMode, &outWavex->Format, NULL);
2939 }
2940
2941 if (hr == S_OK)
2942 {
2943 return paFormatIsSupported;
2944 }
2945 else
2946 if (sharedClosestMatch != NULL)
2947 {
2948 WORD bitsPerSample;
2949
2950 if (sharedClosestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
2951 memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEXTENSIBLE));
2952 else
2953 memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEX));
2954
2955 CoTaskMemFree(sharedClosestMatch);
2956 sharedClosestMatch = NULL;
2957
2958 // Validate SampleRate
2959 if ((DWORD)sampleRate != outWavex->Format.nSamplesPerSec)
2960 return paInvalidSampleRate;
2961
2962 // Validate Channel count
2963 if ((WORD)params.channelCount != outWavex->Format.nChannels)
2964 {
2965 // If mono, then driver does not support 1 channel, we use internal workaround
2966 // of tiny software mixing functionality, e.g. we provide to user buffer 1 channel
2967 // but then mix into 2 for device buffer
2968 if ((params.channelCount == 1) && (outWavex->Format.nChannels == 2))
2969 return paFormatIsSupported;
2970 else
2971 return paInvalidChannelCount;
2972 }
2973
2974 // Validate Sample format
2975 if ((bitsPerSample = PaSampleFormatToBitsPerSample(params.sampleFormat)) == 0)
2976 return paSampleFormatNotSupported;
2977
2978 // Accepted format
2979 return paFormatIsSupported;
2980 }
2981 else
2982 if ((shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) && !explicitFormat)
2983 {
2984 // Try standard approach, e.g. if data is > 16 bits it will be packed into 32-bit containers
2985 if ((hr = GetAlternativeSampleFormatExclusive(client, sampleRate, &params, outWavex, FALSE)) == S_OK)
2986 return paFormatIsSupported;
2987
2988 // Enforce packed only format, e.g. data bits will not be packed into 32-bit containers in any case
2989 if ((hr = GetAlternativeSampleFormatExclusive(client, sampleRate, &params, outWavex, TRUE)) == S_OK)
2990 return paFormatIsSupported;
2991
2992 // Log failure
2993 LogHostError(hr);
2994 }
2995 else
2996 {
2997 // Exclusive mode and requested strict format, WASAPI did not accept this sample format
2998 LogHostError(hr);
2999 }
3000
3001 return paInvalidSampleRate;
3002 }
3003
3004 // ------------------------------------------------------------------------------------------
3005 static PaError IsStreamParamsValid(struct PaUtilHostApiRepresentation *hostApi,
3006 const PaStreamParameters *inputParameters,
3007 const PaStreamParameters *outputParameters,
3008 double sampleRate)
3009 {
3010 if (hostApi == NULL)
3011 return paHostApiNotFound;
3012 if ((UINT32)sampleRate == 0)
3013 return paInvalidSampleRate;
3014
3015 if (inputParameters != NULL)
3016 {
3017 /* all standard sample formats are supported by the buffer adapter,
3018 this implementation doesn't support any custom sample formats */
3019 // Note: paCustomFormat is now 8.24 (24-bits in 32-bit containers)
3020 //if (inputParameters->sampleFormat & paCustomFormat)
3021 // return paSampleFormatNotSupported;
3022
3023 /* unless alternate device specification is supported, reject the use of
3024 paUseHostApiSpecificDeviceSpecification */
3025 if (inputParameters->device == paUseHostApiSpecificDeviceSpecification)
3026 return paInvalidDevice;
3027
3028 /* check that input device can support inputChannelCount */
3029 if (inputParameters->channelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels)
3030 return paInvalidChannelCount;
3031
3032 /* validate inputStreamInfo */
3033 if (inputParameters->hostApiSpecificStreamInfo)
3034 {
3035 PaWasapiStreamInfo *inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
3036 if ((inputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
3037 (inputStreamInfo->version != 1) ||
3038 (inputStreamInfo->hostApiType != paWASAPI))
3039 {
3040 return paIncompatibleHostApiSpecificStreamInfo;
3041 }
3042 }
3043
3044 return paNoError;
3045 }
3046
3047 if (outputParameters != NULL)
3048 {
3049 /* all standard sample formats are supported by the buffer adapter,
3050 this implementation doesn't support any custom sample formats */
3051 // Note: paCustomFormat is now 8.24 (24-bits in 32-bit containers)
3052 //if (outputParameters->sampleFormat & paCustomFormat)
3053 // return paSampleFormatNotSupported;
3054
3055 /* unless alternate device specification is supported, reject the use of
3056 paUseHostApiSpecificDeviceSpecification */
3057 if (outputParameters->device == paUseHostApiSpecificDeviceSpecification)
3058 return paInvalidDevice;
3059
3060 /* check that output device can support outputChannelCount */
3061 if (outputParameters->channelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels)
3062 return paInvalidChannelCount;
3063
3064 /* validate outputStreamInfo */
3065 if(outputParameters->hostApiSpecificStreamInfo)
3066 {
3067 PaWasapiStreamInfo *outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
3068 if ((outputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
3069 (outputStreamInfo->version != 1) ||
3070 (outputStreamInfo->hostApiType != paWASAPI))
3071 {
3072 return paIncompatibleHostApiSpecificStreamInfo;
3073 }
3074 }
3075
3076 return paNoError;
3077 }
3078
3079 return (inputParameters || outputParameters ? paNoError : paInternalError);
3080 }
3081
3082 // ------------------------------------------------------------------------------------------
3083 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
3084 const PaStreamParameters *inputParameters,
3085 const PaStreamParameters *outputParameters,
3086 double sampleRate )
3087 {
3088 IAudioClient *tmpClient = NULL;
3089 PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
3090 PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
3091
3092 // Validate PaStreamParameters
3093 PaError error;
3094 if ((error = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
3095 return error;
3096
3097 if (inputParameters != NULL)
3098 {
3099 WAVEFORMATEXTENSIBLE wavex;
3100 HRESULT hr;
3101 PaError answer;
3102 AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
3103 inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
3104
3105 if (inputStreamInfo && (inputStreamInfo->flags & paWinWasapiExclusive))
3106 shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
3107
3108 hr = ActivateAudioInterface(&paWasapi->devInfo[inputParameters->device], inputStreamInfo, &tmpClient);
3109 if (hr != S_OK)
3110 {
3111 LogHostError(hr);
3112 return paInvalidDevice;
3113 }
3114
3115 answer = GetClosestFormat(tmpClient, sampleRate, inputParameters, shareMode, &wavex, FALSE);
3116 SAFE_RELEASE(tmpClient);
3117
3118 if (answer != paFormatIsSupported)
3119 return answer;
3120 }
3121
3122 if (outputParameters != NULL)
3123 {
3124 HRESULT hr;
3125 WAVEFORMATEXTENSIBLE wavex;
3126 PaError answer;
3127 AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
3128 outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
3129
3130 if (outputStreamInfo && (outputStreamInfo->flags & paWinWasapiExclusive))
3131 shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
3132
3133 hr = ActivateAudioInterface(&paWasapi->devInfo[outputParameters->device], outputStreamInfo, &tmpClient);
3134 if (hr != S_OK)
3135 {
3136 LogHostError(hr);
3137 return paInvalidDevice;
3138 }
3139
3140 answer = GetClosestFormat(tmpClient, sampleRate, outputParameters, shareMode, &wavex, TRUE);
3141 SAFE_RELEASE(tmpClient);
3142
3143 if (answer != paFormatIsSupported)
3144 return answer;
3145 }
3146
3147 return paFormatIsSupported;
3148 }
3149
3150 // ------------------------------------------------------------------------------------------
3151 static PaUint32 _GetFramesPerHostBuffer(PaUint32 userFramesPerBuffer, PaTime suggestedLatency, double sampleRate, PaUint32 TimerJitterMs)
3152 {
3153 PaUint32 frames = userFramesPerBuffer + max( userFramesPerBuffer, (PaUint32)(suggestedLatency * sampleRate) );
3154 frames += (PaUint32)((sampleRate * 0.001) * TimerJitterMs);
3155 return frames;
3156 }
3157
3158 // ------------------------------------------------------------------------------------------
3159 static void _RecalculateBuffersCount(PaWasapiSubStream *sub, UINT32 userFramesPerBuffer, UINT32 framesPerLatency,
3160 BOOL fullDuplex, BOOL output)
3161 {
3162 // Count buffers (must be at least 1)
3163 sub->buffers = (userFramesPerBuffer != 0 ? framesPerLatency / userFramesPerBuffer : 1);
3164 if (sub->buffers == 0)
3165 sub->buffers = 1;
3166
3167 // Determine number of buffers used:
3168 // - Full-duplex mode will lead to period difference, thus only 1
3169 // - Input mode, only 1, as WASAPI allows extraction of only 1 packet
3170 // - For Shared mode we use double buffering
3171 if ((sub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) || fullDuplex)
3172 {
3173 BOOL eventMode = ((sub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == AUDCLNT_STREAMFLAGS_EVENTCALLBACK);
3174
3175 // Exclusive mode does not allow >1 buffers be used for Event interface, e.g. GetBuffer
3176 // call must acquire max buffer size and it all must be processed.
3177 if (eventMode)
3178 sub->userBufferAndHostMatch = 1;
3179
3180 // Full-duplex or Event mode: prefer paUtilBoundedHostBufferSize because exclusive mode will starve
3181 // and produce glitchy audio
3182 // Output Polling mode: prefer paUtilFixedHostBufferSize (buffers != 1) for polling mode is it allows
3183 // to consume user data by fixed size data chunks and thus lowers memory movement (less CPU usage)
3184 if (fullDuplex || eventMode || !output)
3185 sub->buffers = 1;
3186 }
3187 }
3188
3189 // ------------------------------------------------------------------------------------------
3190 static void _CalculateAlignedPeriod(PaWasapiSubStream *pSub, UINT32 *nFramesPerLatency, ALIGN_FUNC pAlignFunc)
3191 {
3192 // Align frames to HD Audio packet size of 128 bytes for Exclusive mode only.
3193 // Not aligning on Windows Vista will cause Event timeout, although Windows 7 will
3194 // return AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED error to realign buffer. Aligning is necessary
3195 // for Exclusive mode only! when audio data is fed directly to hardware.
3196 if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
3197 {
3198 (*nFramesPerLatency) = AlignFramesPerBuffer((*nFramesPerLatency),
3199 pSub->wavex.Format.nBlockAlign, pAlignFunc);
3200 }
3201
3202 // Calculate period
3203 pSub->period = MakeHnsPeriod((*nFramesPerLatency), pSub->wavex.Format.nSamplesPerSec);
3204 }
3205
3206 // ------------------------------------------------------------------------------------------
3207 static void _CalculatePeriodicity(PaWasapiSubStream *pSub, BOOL output, REFERENCE_TIME *periodicity)
3208 {
3209 // Note: according to Microsoft docs for IAudioClient::Initialize we can set periodicity of the buffer
3210 // only for Exclusive mode. By setting periodicity almost equal to the user buffer frames we can
3211 // achieve high quality (less glitchy) low-latency audio.
3212 if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
3213 {
3214 const PaWasapiDeviceInfo *pInfo = pSub->params.device_info;
3215
3216 // By default periodicity equals to the full buffer (legacy PA WASAPI's behavior)
3217 (*periodicity) = pSub->period;
3218
3219 // Try make buffer ready for I/O once we request the buffer readiness for it. Only Polling mode
3220 // because for Event mode buffer size and periodicity must be equal according to Microsoft
3221 // documentation for IAudioClient::Initialize.
3222 //
3223 // TO-DO: try spread to capture and full-duplex cases (not tested and therefore disabled)
3224 //
3225 if (((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0) &&
3226 (output && !pSub->params.full_duplex))
3227 {
3228 UINT32 alignedFrames;
3229 REFERENCE_TIME userPeriodicity;
3230
3231 // Align frames backwards, so device will likely make buffer read ready when we are ready
3232 // to read it (our scheduling will wait for amount of millisoconds of frames_per_buffer)
3233 alignedFrames = AlignFramesPerBuffer(pSub->params.frames_per_buffer,
3234 pSub->wavex.Format.nBlockAlign, ALIGN_BWD);
3235
3236 userPeriodicity = MakeHnsPeriod(alignedFrames, pSub->wavex.Format.nSamplesPerSec);
3237
3238 // Must not be larger than buffer size
3239 if (userPeriodicity > pSub->period)
3240 userPeriodicity = pSub->period;
3241
3242 // Must not be smaller than minimum supported by the device
3243 if (userPeriodicity < pInfo->MinimumDevicePeriod)
3244 userPeriodicity = pInfo->MinimumDevicePeriod;
3245
3246 (*periodicity) = userPeriodicity;
3247 }
3248 }
3249 else
3250 (*periodicity) = 0;
3251 }
3252
3253 // ------------------------------------------------------------------------------------------
3254 static HRESULT CreateAudioClient(PaWasapiStream *pStream, PaWasapiSubStream *pSub, BOOL output, PaError *pa_error)
3255 {
3256 PaError error;
3257 HRESULT hr;
3258 const PaWasapiDeviceInfo *pInfo = pSub->params.device_info;
3259 const PaStreamParameters *params = &pSub->params.stream_params;
3260 const double sampleRate = pSub->params.sample_rate;
3261 const BOOL fullDuplex = pSub->params.full_duplex;
3262 const UINT32 userFramesPerBuffer = pSub->params.frames_per_buffer;
3263 UINT32 framesPerLatency = userFramesPerBuffer;
3264 IAudioClient *audioClient = NULL;
3265 REFERENCE_TIME eventPeriodicity = 0;
3266
3267 // Assume default failure due to some reason
3268 (*pa_error) = paInvalidDevice;
3269
3270 // Validate parameters
3271 if (!pSub || !pInfo || !params)
3272 {
3273 (*pa_error) = paBadStreamPtr;
3274 return E_POINTER;
3275 }
3276 if ((UINT32)sampleRate == 0)
3277 {
3278 (*pa_error) = paInvalidSampleRate;
3279 return E_INVALIDARG;
3280 }
3281
3282 // Get the audio client
3283 if (FAILED(hr = ActivateAudioInterface(pInfo, &pSub->params.wasapi_params, &audioClient)))
3284 {
3285 (*pa_error) = paInsufficientMemory;
3286 LogHostError(hr);
3287 goto done;
3288 }
3289
3290 // Get closest format
3291 if ((error = GetClosestFormat(audioClient, sampleRate, params, pSub->shareMode, &pSub->wavex, output)) != paFormatIsSupported)
3292 {
3293 (*pa_error) = error;
3294 LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
3295 goto done; // fail, format not supported
3296 }
3297
3298 // Check for Mono <<>> Stereo workaround
3299 if ((params->channelCount == 1) && (pSub->wavex.Format.nChannels == 2))
3300 {
3301 // select mixer
3302 pSub->monoMixer = GetMonoToStereoMixer(&pSub->wavex, (pInfo->flow == eRender ? MIX_DIR__1TO2 : MIX_DIR__2TO1_L));
3303 if (pSub->monoMixer == NULL)
3304 {
3305 (*pa_error) = paInvalidChannelCount;
3306 LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
3307 goto done; // fail, no mixer for format
3308 }
3309 }
3310
3311 // Calculate host buffer size
3312 if ((pSub->shareMode != AUDCLNT_SHAREMODE_EXCLUSIVE) &&
3313 (!pSub->streamFlags || ((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
3314 {
3315 framesPerLatency = _GetFramesPerHostBuffer(userFramesPerBuffer,
3316 params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
3317 (pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
3318 }
3319 else
3320 {
3321 #ifdef PA_WASAPI_FORCE_POLL_IF_LARGE_BUFFER
3322 REFERENCE_TIME overall;
3323 #endif
3324
3325 // Work 1:1 with user buffer (only polling allows to use >1)
3326 framesPerLatency += MakeFramesFromHns(SecondsTonano100(params->suggestedLatency), pSub->wavex.Format.nSamplesPerSec);
3327
3328 // Force Polling if overall latency is >= 21.33ms as it allows to use 100% CPU in a callback,
3329 // or user specified latency parameter.
3330 #ifdef PA_WASAPI_FORCE_POLL_IF_LARGE_BUFFER
3331 overall = MakeHnsPeriod(framesPerLatency, pSub->wavex.Format.nSamplesPerSec);
3332 if (overall >= (106667 * 2)/*21.33ms*/)
3333 {
3334 framesPerLatency = _GetFramesPerHostBuffer(userFramesPerBuffer,
3335 params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
3336 (streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
3337
3338 // Use Polling interface
3339 pSub->streamFlags &= ~AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
3340 PRINT(("WASAPI: CreateAudioClient: forcing POLL mode\n"));
3341 }
3342 #endif
3343 }
3344
3345 // For full-duplex output resize buffer to be the same as for input
3346 if (output && fullDuplex)
3347 framesPerLatency = pStream->in.framesPerHostCallback;
3348
3349 // Avoid 0 frames
3350 if (framesPerLatency == 0)
3351 framesPerLatency = MakeFramesFromHns(pInfo->DefaultDevicePeriod, pSub->wavex.Format.nSamplesPerSec);
3352
3353 // Exclusive Input stream renders data in 6 packets, we must set then the size of
3354 // single packet, total buffer size, e.g. required latency will be PacketSize * 6
3355 if (!output && (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE))
3356 {
3357 // Do it only for Polling mode
3358 if ((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)
3359 framesPerLatency /= WASAPI_PACKETS_PER_INPUT_BUFFER;
3360 }
3361
3362 // Calculate aligned period
3363 _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
3364
3365 /*! Enforce min/max period for device in Shared mode to avoid bad audio quality.
3366 Avoid doing so for Exclusive mode as alignment will suffer.
3367 */
3368 if (pSub->shareMode == AUDCLNT_SHAREMODE_SHARED)
3369 {
3370 if (pSub->period < pInfo->DefaultDevicePeriod)
3371 {
3372 pSub->period = pInfo->DefaultDevicePeriod;
3373
3374 // Recalculate aligned period
3375 framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
3376 _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
3377 }
3378 }
3379 else
3380 {
3381 if (pSub->period < pInfo->MinimumDevicePeriod)
3382 {
3383 pSub->period = pInfo->MinimumDevicePeriod;
3384
3385 // Recalculate aligned period
3386 framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
3387 _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_FWD);
3388 }
3389 }
3390
3391 /*! Windows 7 does not allow to set latency lower than minimal device period and will
3392 return error: AUDCLNT_E_INVALID_DEVICE_PERIOD. Under Vista we enforce the same behavior
3393 manually for unified behavior on all platforms.
3394 */
3395 {
3396 /*! AUDCLNT_E_BUFFER_SIZE_ERROR: Applies to Windows 7 and later.
3397 Indicates that the buffer duration value requested by an exclusive-mode client is
3398 out of range. The requested duration value for pull mode must not be greater than
3399 500 milliseconds; for push mode the duration value must not be greater than 2 seconds.
3400 */
3401 if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
3402 {
3403 static const REFERENCE_TIME MAX_BUFFER_EVENT_DURATION = 500 * 10000;
3404 static const REFERENCE_TIME MAX_BUFFER_POLL_DURATION = 2000 * 10000;
3405
3406 // Pull mode, max 500ms
3407 if (pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)
3408 {
3409 if (pSub->period > MAX_BUFFER_EVENT_DURATION)
3410 {
3411 pSub->period = MAX_BUFFER_EVENT_DURATION;
3412
3413 // Recalculate aligned period
3414 framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
3415 _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
3416 }
3417 }
3418 // Push mode, max 2000ms
3419 else
3420 {
3421 if (pSub->period > MAX_BUFFER_POLL_DURATION)
3422 {
3423 pSub->period = MAX_BUFFER_POLL_DURATION;
3424
3425 // Recalculate aligned period
3426 framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
3427 _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
3428 }
3429 }
3430 }
3431 }
3432
3433 // Set device scheduling period (always 0 in Shared mode according to Microsoft docs)
3434 _CalculatePeriodicity(pSub, output, &eventPeriodicity);
3435
3436 // Open the stream and associate it with an audio session
3437 hr = IAudioClient_Initialize(audioClient,
3438 pSub->shareMode,
3439 pSub->streamFlags,
3440 pSub->period,
3441 eventPeriodicity,
3442 &pSub->wavex.Format,
3443 NULL);
3444
3445 // [Output only] Check if buffer size is the one we requested in Exclusive mode, for UAC1 USB DACs WASAPI
3446 // can allocate internal buffer equal to 8 times of pSub->period that has to be corrected in order to match
3447 // the requested latency
3448 if (output && SUCCEEDED(hr) && (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE))
3449 {
3450 UINT32 maxBufferFrames;
3451
3452 if (FAILED(hr = IAudioClient_GetBufferSize(audioClient, &maxBufferFrames)))
3453 {
3454 (*pa_error) = paInvalidDevice;
3455 LogHostError(hr);
3456 goto done;
3457 }
3458
3459 // For Exclusive mode for UAC1 devices maxBufferFrames may be framesPerLatency * 8 but check any difference
3460 // to be able to guarantee the latency user requested and also resulted framesPerLatency may be bigger than
3461 // 2 seconds that will cause audio client not operational (GetCurrentPadding() will return always 0)
3462 if (maxBufferFrames >= (framesPerLatency * 2))
3463 {
3464 UINT32 ratio = maxBufferFrames / framesPerLatency;
3465
3466 PRINT(("WASAPI: CreateAudioClient: detected %d times larger buffer than requested, correct to match user latency\n", ratio));
3467
3468 // Get new aligned frames lowered by calculated ratio
3469 framesPerLatency = MakeFramesFromHns(pSub->period / ratio, pSub->wavex.Format.nSamplesPerSec);
3470 _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
3471
3472 // Make sure we are not below the minimum period
3473 if (pSub->period < pInfo->MinimumDevicePeriod)
3474 pSub->period = pInfo->MinimumDevicePeriod;
3475
3476 // Release previous client
3477 SAFE_RELEASE(audioClient);
3478
3479 // Create a new audio client
3480 if (FAILED(hr = ActivateAudioInterface(pInfo, &pSub->params.wasapi_params, &audioClient)))
3481 {
3482 (*pa_error) = paInsufficientMemory;
3483 LogHostError(hr);
3484 goto done;
3485 }
3486
3487 // Set device scheduling period (always 0 in Shared mode according to Microsoft docs)
3488 _CalculatePeriodicity(pSub, output, &eventPeriodicity);
3489
3490 // Open the stream and associate it with an audio session
3491 hr = IAudioClient_Initialize(audioClient,
3492 pSub->shareMode,
3493 pSub->streamFlags,
3494 pSub->period,
3495 eventPeriodicity,
3496 &pSub->wavex.Format,
3497 NULL);
3498 }
3499 }
3500
3501 /*! WASAPI is tricky on large device buffer, sometimes 2000ms can be allocated sometimes
3502 less. There is no known guaranteed level thus we make subsequent tries by decreasing
3503 buffer by 100ms per try.
3504 */
3505 while ((hr == E_OUTOFMEMORY) && (pSub->period > (100 * 10000)))
3506 {
3507 PRINT(("WASAPI: CreateAudioClient: decreasing buffer size to %d milliseconds\n", (pSub->period / 10000)));
3508
3509 // Decrease by 100ms and try again
3510 pSub->period -= (100 * 10000);
3511
3512 // Recalculate aligned period
3513 framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
3514 _CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
3515
3516 // Release the previous allocations
3517 SAFE_RELEASE(audioClient);
3518
3519 // Create a new audio client
3520 if (FAILED(hr = ActivateAudioInterface(pInfo, &pSub->params.wasapi_params, &audioClient)))
3521 {
3522 (*pa_error) = paInsufficientMemory;
3523 LogHostError(hr);
3524 goto done;
3525 }
3526
3527 // Set device scheduling period (always 0 in Shared mode according to Microsoft docs)
3528 _CalculatePeriodicity(pSub, output, &eventPeriodicity);
3529
3530 // Open the stream and associate it with an audio session
3531 hr = IAudioClient_Initialize(audioClient,
3532 pSub->shareMode,
3533 pSub->streamFlags,
3534 pSub->period,
3535 eventPeriodicity,
3536 &pSub->wavex.Format,
3537 NULL);
3538 }
3539
3540 /*! WASAPI buffer size or alignment failure. Fallback to using default size and alignment.
3541 */
3542 if ((hr == AUDCLNT_E_BUFFER_SIZE_ERROR) || (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED))
3543 {
3544 // Use default
3545 pSub->period = pInfo->DefaultDevicePeriod;
3546
3547 PRINT(("WASAPI: CreateAudioClient: correcting buffer size/alignment to device default\n"));
3548
3549 // Release the previous allocations
3550 SAFE_RELEASE(audioClient);
3551
3552 // Create a new audio client
3553 if (FAILED(hr = ActivateAudioInterface(pInfo, &pSub->params.wasapi_params, &audioClient)))
3554 {
3555 (*pa_error) = paInsufficientMemory;
3556 LogHostError(hr);
3557 goto done;
3558 }
3559
3560 // Set device scheduling period (always 0 in Shared mode according to Microsoft docs)
3561 _CalculatePeriodicity(pSub, output, &eventPeriodicity);
3562
3563 // Open the stream and associate it with an audio session
3564 hr = IAudioClient_Initialize(audioClient,
3565 pSub->shareMode,
3566 pSub->streamFlags,
3567 pSub->period,
3568 eventPeriodicity,
3569 &pSub->wavex.Format,
3570 NULL);
3571 }
3572
3573 // Error has no workaround, fail completely
3574 if (FAILED(hr))
3575 {
3576 (*pa_error) = paInvalidDevice;
3577 LogHostError(hr);
3578 goto done;
3579 }
3580
3581 // Set client
3582 pSub->clientParent = audioClient;
3583 IAudioClient_AddRef(pSub->clientParent);
3584
3585 // Recalculate buffers count
3586 _RecalculateBuffersCount(pSub, userFramesPerBuffer, MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec),
3587 fullDuplex, output);
3588
3589 // No error, client is successfully created
3590 (*pa_error) = paNoError;
3591
3592 done:
3593
3594 // Clean up
3595 SAFE_RELEASE(audioClient);
3596 return hr;
3597 }
3598
3599 // ------------------------------------------------------------------------------------------
3600 static PaError ActivateAudioClientOutput(PaWasapiStream *stream)
3601 {
3602 HRESULT hr;
3603 PaError result;
3604 UINT32 maxBufferSize;
3605 PaTime bufferLatency;
3606 const UINT32 framesPerBuffer = stream->out.params.frames_per_buffer;
3607
3608 // Create Audio client
3609 if (FAILED(hr = CreateAudioClient(stream, &stream->out, TRUE, &result)))
3610 {
3611 LogPaError(result);
3612 goto error;
3613 }
3614 LogWAVEFORMATEXTENSIBLE(&stream->out.wavex);
3615
3616 // Activate volume
3617 stream->outVol = NULL;
3618 /*hr = info->device->Activate(
3619 __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
3620 (void**)&stream->outVol);
3621 if (hr != S_OK)
3622 return paInvalidDevice;*/
3623
3624 // Get max possible buffer size to check if it is not less than that we request
3625 if (FAILED(hr = IAudioClient_GetBufferSize(stream->out.clientParent, &maxBufferSize)))
3626 {
3627 LogHostError(hr);
3628 LogPaError(result = paInvalidDevice);
3629 goto error;
3630 }
3631
3632 // Correct buffer to max size if it maxed out result of GetBufferSize
3633 stream->out.bufferSize = maxBufferSize;
3634
3635 // Number of frames that are required at each period
3636 stream->out.framesPerHostCallback = maxBufferSize;
3637
3638 // Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
3639 stream->out.framesPerBuffer =
3640 (stream->out.userBufferAndHostMatch ? stream->out.framesPerHostCallback : framesPerBuffer);
3641
3642 // Calculate buffer latency
3643 bufferLatency = (PaTime)maxBufferSize / stream->out.wavex.Format.nSamplesPerSec;
3644
3645 // Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
3646 stream->out.latencySeconds = bufferLatency;
3647
3648 PRINT(("WASAPI::OpenStream(output): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->out.framesPerHostCallback, (float)(stream->out.latencySeconds*1000.0f), (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (stream->out.params.wow64_workaround ? "YES" : "NO"), (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
3649
3650 return paNoError;
3651
3652 error:
3653
3654 return result;
3655 }
3656
3657 // ------------------------------------------------------------------------------------------
3658 static PaError ActivateAudioClientInput(PaWasapiStream *stream)
3659 {
3660 HRESULT hr;
3661 PaError result;
3662 UINT32 maxBufferSize;
3663 PaTime bufferLatency;
3664 const UINT32 framesPerBuffer = stream->in.params.frames_per_buffer;
3665
3666 // Create Audio client
3667 if (FAILED(hr = CreateAudioClient(stream, &stream->in, FALSE, &result)))
3668 {
3669 LogPaError(result);
3670 goto error;
3671 }
3672 LogWAVEFORMATEXTENSIBLE(&stream->in.wavex);
3673
3674 // Create volume mgr
3675 stream->inVol = NULL;
3676 /*hr = info->device->Activate(
3677 __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
3678 (void**)&stream->inVol);
3679 if (hr != S_OK)
3680 return paInvalidDevice;*/
3681
3682 // Get max possible buffer size to check if it is not less than that we request
3683 if (FAILED(hr = IAudioClient_GetBufferSize(stream->in.clientParent, &maxBufferSize)))
3684 {
3685 LogHostError(hr);
3686 LogPaError(result = paInvalidDevice);
3687 goto error;
3688 }
3689
3690 // Correct buffer to max size if it maxed out result of GetBufferSize
3691 stream->in.bufferSize = maxBufferSize;
3692
3693 // Get interface latency (actually unneeded as we calculate latency from the size
3694 // of maxBufferSize).
3695 if (FAILED(hr = IAudioClient_GetStreamLatency(stream->in.clientParent, &stream->in.deviceLatency)))
3696 {
3697 LogHostError(hr);
3698 LogPaError(result = paInvalidDevice);
3699 goto error;
3700 }
3701 //stream->in.latencySeconds = nano100ToSeconds(stream->in.deviceLatency);
3702
3703 // Number of frames that are required at each period
3704 stream->in.framesPerHostCallback = maxBufferSize;
3705
3706 // Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
3707 stream->in.framesPerBuffer =
3708 (stream->in.userBufferAndHostMatch ? stream->in.framesPerHostCallback : framesPerBuffer);
3709
3710 // Calculate buffer latency
3711 bufferLatency = (PaTime)maxBufferSize / stream->in.wavex.Format.nSamplesPerSec;
3712
3713 // Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
3714 stream->in.latencySeconds = bufferLatency;
3715
3716 PRINT(("WASAPI::OpenStream(input): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->in.framesPerHostCallback, (float)(stream->in.latencySeconds*1000.0f), (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (stream->in.params.wow64_workaround ? "YES" : "NO"), (stream->in.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
3717
3718 return paNoError;
3719
3720 error:
3721
3722 return result;
3723 }
3724
3725 // ------------------------------------------------------------------------------------------
3726 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
3727 PaStream** s,
3728 const PaStreamParameters *inputParameters,
3729 const PaStreamParameters *outputParameters,
3730 double sampleRate,
3731 unsigned long framesPerBuffer,
3732 PaStreamFlags streamFlags,
3733 PaStreamCallback *streamCallback,
3734 void *userData )
3735 {
3736 PaError result = paNoError;
3737 HRESULT hr;
3738 PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
3739 PaWasapiStream *stream = NULL;
3740 int inputChannelCount, outputChannelCount;
3741 PaSampleFormat inputSampleFormat, outputSampleFormat;
3742 PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
3743 PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
3744 PaWasapiDeviceInfo *info = NULL;
3745 ULONG framesPerHostCallback;
3746 PaUtilHostBufferSizeMode bufferMode;
3747 const BOOL fullDuplex = ((inputParameters != NULL) && (outputParameters != NULL));
3748 BOOL useInputBufferProcessor = (inputParameters != NULL), useOutputBufferProcessor = (outputParameters != NULL);
3749
3750 // validate PaStreamParameters
3751 if ((result = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
3752 return LogPaError(result);
3753
3754 // Validate platform specific flags
3755 if ((streamFlags & paPlatformSpecificFlags) != 0)
3756 {
3757 LogPaError(result = paInvalidFlag); /* unexpected platform specific flag */
3758 goto error;
3759 }
3760
3761 // Allocate memory for PaWasapiStream
3762 if ((stream = (PaWasapiStream *)PaUtil_AllocateMemory(sizeof(PaWasapiStream))) == NULL)
3763 {
3764 LogPaError(result = paInsufficientMemory);
3765 goto error;
3766 }
3767
3768 // Default thread priority is Audio: for exclusive mode we will use Pro Audio.
3769 stream->nThreadPriority = eThreadPriorityAudio;
3770
3771 // Set default number of frames: paFramesPerBufferUnspecified
3772 if (framesPerBuffer == paFramesPerBufferUnspecified)
3773 {
3774 UINT32 framesPerBufferIn = 0, framesPerBufferOut = 0;
3775 if (inputParameters != NULL)
3776 {
3777 info = &paWasapi->devInfo[inputParameters->device];
3778 framesPerBufferIn = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
3779 }
3780 if (outputParameters != NULL)
3781 {
3782 info = &paWasapi->devInfo[outputParameters->device];
3783 framesPerBufferOut = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
3784 }
3785 // choosing maximum default size
3786 framesPerBuffer = max(framesPerBufferIn, framesPerBufferOut);
3787 }
3788 if (framesPerBuffer == 0)
3789 framesPerBuffer = ((UINT32)sampleRate / 100) * 2;
3790
3791 // Try create device: Input
3792 if (inputParameters != NULL)
3793 {
3794 inputChannelCount = inputParameters->channelCount;
3795 inputSampleFormat = GetSampleFormatForIO(inputParameters->sampleFormat);
3796 info = &paWasapi->devInfo[inputParameters->device];
3797
3798 // default Shared Mode
3799 stream->in.shareMode = AUDCLNT_SHAREMODE_SHARED;
3800
3801 // PaWasapiStreamInfo
3802 if (inputParameters->hostApiSpecificStreamInfo != NULL)
3803 {
3804 memcpy(&stream->in.params.wasapi_params, inputParameters->hostApiSpecificStreamInfo, min(sizeof(stream->in.params.wasapi_params), ((PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo)->size));
3805 stream->in.params.wasapi_params.size = sizeof(stream->in.params.wasapi_params);
3806
3807 stream->in.params.stream_params.hostApiSpecificStreamInfo = &stream->in.params.wasapi_params;
3808 inputStreamInfo = &stream->in.params.wasapi_params;
3809
3810 stream->in.flags = inputStreamInfo->flags;
3811
3812 // Exclusive Mode
3813 if (inputStreamInfo->flags & paWinWasapiExclusive)
3814 {
3815 // Boost thread priority
3816 stream->nThreadPriority = eThreadPriorityProAudio;
3817 // Make Exclusive
3818 stream->in.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
3819 }
3820
3821 // explicit thread priority level
3822 if (inputStreamInfo->flags & paWinWasapiThreadPriority)
3823 {
3824 if ((inputStreamInfo->threadPriority > eThreadPriorityNone) &&
3825 (inputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
3826 stream->nThreadPriority = inputStreamInfo->threadPriority;
3827 }
3828
3829 // redirect processing to custom user callback, ignore PA buffer processor
3830 useInputBufferProcessor = !(inputStreamInfo->flags & paWinWasapiRedirectHostProcessor);
3831 }
3832
3833 // Choose processing mode
3834 stream->in.streamFlags = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
3835 if (paWasapi->useWOW64Workaround)
3836 stream->in.streamFlags = 0; // polling interface
3837 else
3838 if (streamCallback == NULL)
3839 stream->in.streamFlags = 0; // polling interface
3840 else
3841 if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiPolling))
3842 stream->in.streamFlags = 0; // polling interface
3843 else
3844 if (fullDuplex)
3845 stream->in.streamFlags = 0; // polling interface is implemented for full-duplex mode also
3846
3847 // Use built-in PCM converter (channel count and sample rate) if requested
3848 if ((GetWindowsVersion() >= WINDOWS_7_SERVER2008R2) &&
3849 (stream->in.shareMode == AUDCLNT_SHAREMODE_SHARED) &&
3850 ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiAutoConvert)))
3851 stream->in.streamFlags |= (AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY);
3852
3853 // Fill parameters for Audio Client creation
3854 stream->in.params.device_info = info;
3855 stream->in.params.stream_params = (*inputParameters);
3856 stream->in.params.frames_per_buffer = framesPerBuffer;
3857 stream->in.params.sample_rate = sampleRate;
3858 stream->in.params.blocking = (streamCallback == NULL);
3859 stream->in.params.full_duplex = fullDuplex;
3860 stream->in.params.wow64_workaround = paWasapi->useWOW64Workaround;
3861
3862 // Create and activate audio client
3863 if ((result = ActivateAudioClientInput(stream)) != paNoError)
3864 {
3865 LogPaError(result);
3866 goto error;
3867 }
3868
3869 // Get closest format
3870 hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat(WaveToPaFormat(&stream->in.wavex), inputSampleFormat);
3871
3872 // Set user-side custom host processor
3873 if ((inputStreamInfo != NULL) &&
3874 (inputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
3875 {
3876 stream->hostProcessOverrideInput.processor = inputStreamInfo->hostProcessorInput;
3877 stream->hostProcessOverrideInput.userData = userData;
3878 }
3879
3880 // Only get IAudioCaptureClient input once here instead of getting it at multiple places based on the use
3881 if (FAILED(hr = IAudioClient_GetService(stream->in.clientParent, &pa_IID_IAudioCaptureClient, (void **)&stream->captureClientParent)))
3882 {
3883 LogHostError(hr);
3884 LogPaError(result = paUnanticipatedHostError);
3885 goto error;
3886 }
3887
3888 // Create ring buffer for blocking mode (It is needed because we fetch Input packets, not frames,
3889 // and thus we have to save partial packet if such remains unread)
3890 if (stream->in.params.blocking == TRUE)
3891 {
3892 UINT32 bufferFrames = ALIGN_NEXT_POW2((stream->in.framesPerHostCallback / WASAPI_PACKETS_PER_INPUT_BUFFER) * 2);
3893 UINT32 frameSize = stream->in.wavex.Format.nBlockAlign;
3894
3895 // buffer
3896 if ((stream->in.tailBuffer = PaUtil_AllocateMemory(sizeof(PaUtilRingBuffer))) == NULL)
3897 {
3898 LogPaError(result = paInsufficientMemory);
3899 goto error;
3900 }
3901 memset(stream->in.tailBuffer, 0, sizeof(PaUtilRingBuffer));
3902
3903 // buffer memory region
3904 stream->in.tailBufferMemory = PaUtil_AllocateMemory(frameSize * bufferFrames);
3905 if (stream->in.tailBufferMemory == NULL)
3906 {
3907 LogPaError(result = paInsufficientMemory);
3908 goto error;
3909 }
3910
3911 // initialize
3912 if (PaUtil_InitializeRingBuffer(stream->in.tailBuffer, frameSize, bufferFrames, stream->in.tailBufferMemory) != 0)
3913 {
3914 LogPaError(result = paInternalError);
3915 goto error;
3916 }
3917 }
3918 }
3919 else
3920 {
3921 inputChannelCount = 0;
3922 inputSampleFormat = hostInputSampleFormat = paInt16; /* Suppress 'uninitialised var' warnings. */
3923 }
3924
3925 // Try create device: Output
3926 if (outputParameters != NULL)
3927 {
3928 outputChannelCount = outputParameters->channelCount;
3929 outputSampleFormat = GetSampleFormatForIO(outputParameters->sampleFormat);
3930 info = &paWasapi->devInfo[outputParameters->device];
3931
3932 // default Shared Mode
3933 stream->out.shareMode = AUDCLNT_SHAREMODE_SHARED;
3934
3935 // set PaWasapiStreamInfo
3936 if (outputParameters->hostApiSpecificStreamInfo != NULL)
3937 {
3938 memcpy(&stream->out.params.wasapi_params, outputParameters->hostApiSpecificStreamInfo, min(sizeof(stream->out.params.wasapi_params), ((PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo)->size));
3939 stream->out.params.wasapi_params.size = sizeof(stream->out.params.wasapi_params);
3940
3941 stream->out.params.stream_params.hostApiSpecificStreamInfo = &stream->out.params.wasapi_params;
3942 outputStreamInfo = &stream->out.params.wasapi_params;
3943
3944 stream->out.flags = outputStreamInfo->flags;
3945
3946 // Exclusive Mode
3947 if (outputStreamInfo->flags & paWinWasapiExclusive)
3948 {
3949 // Boost thread priority
3950 stream->nThreadPriority = eThreadPriorityProAudio;
3951 // Make Exclusive
3952 stream->out.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
3953 }
3954
3955 // explicit thread priority level
3956 if (outputStreamInfo->flags & paWinWasapiThreadPriority)
3957 {
3958 if ((outputStreamInfo->threadPriority > eThreadPriorityNone) &&
3959 (outputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
3960 stream->nThreadPriority = outputStreamInfo->threadPriority;
3961 }
3962
3963 // redirect processing to custom user callback, ignore PA buffer processor
3964 useOutputBufferProcessor = !(outputStreamInfo->flags & paWinWasapiRedirectHostProcessor);
3965 }
3966
3967 // Choose processing mode
3968 stream->out.streamFlags = (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
3969 if (paWasapi->useWOW64Workaround)
3970 stream->out.streamFlags = 0; // polling interface
3971 else
3972 if (streamCallback == NULL)
3973 stream->out.streamFlags = 0; // polling interface
3974 else
3975 if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiPolling))
3976 stream->out.streamFlags = 0; // polling interface
3977 else
3978 if (fullDuplex)
3979 stream->out.streamFlags = 0; // polling interface is implemented for full-duplex mode also
3980
3981 // Use built-in PCM converter (channel count and sample rate) if requested
3982 if ((GetWindowsVersion() >= WINDOWS_7_SERVER2008R2) &&
3983 (stream->out.shareMode == AUDCLNT_SHAREMODE_SHARED) &&
3984 ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiAutoConvert)))
3985 stream->out.streamFlags |= (AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY);
3986
3987 // Fill parameters for Audio Client creation
3988 stream->out.params.device_info = info;
3989 stream->out.params.stream_params = (*outputParameters);
3990 stream->out.params.frames_per_buffer = framesPerBuffer;
3991 stream->out.params.sample_rate = sampleRate;
3992 stream->out.params.blocking = (streamCallback == NULL);
3993 stream->out.params.full_duplex = fullDuplex;
3994 stream->out.params.wow64_workaround = paWasapi->useWOW64Workaround;
3995
3996 // Create and activate audio client
3997 if ((result = ActivateAudioClientOutput(stream)) != paNoError)
3998 {
3999 LogPaError(result);
4000 goto error;
4001 }
4002
4003 // Get closest format
4004 hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat(WaveToPaFormat(&stream->out.wavex), outputSampleFormat);
4005
4006 // Set user-side custom host processor
4007 if ((outputStreamInfo != NULL) &&
4008 (outputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
4009 {
4010 stream->hostProcessOverrideOutput.processor = outputStreamInfo->hostProcessorOutput;
4011 stream->hostProcessOverrideOutput.userData = userData;
4012 }
4013
4014 // Only get IAudioCaptureClient output once here instead of getting it at multiple places based on the use
4015 if (FAILED(hr = IAudioClient_GetService(stream->out.clientParent, &pa_IID_IAudioRenderClient, (void **)&stream->renderClientParent)))
4016 {
4017 LogHostError(hr);
4018 LogPaError(result = paUnanticipatedHostError);
4019 goto error;
4020 }
4021 }
4022 else
4023 {
4024 outputChannelCount = 0;
4025 outputSampleFormat = hostOutputSampleFormat = paInt16; /* Suppress 'uninitialized var' warnings. */
4026 }
4027
4028 // log full-duplex
4029 if (fullDuplex)
4030 PRINT(("WASAPI::OpenStream: full-duplex mode\n"));
4031
4032 // paWinWasapiPolling must be on/or not on both streams
4033 if ((inputParameters != NULL) && (outputParameters != NULL))
4034 {
4035 if ((inputStreamInfo != NULL) && (outputStreamInfo != NULL))
4036 {
4037 if (((inputStreamInfo->flags & paWinWasapiPolling) &&
4038 !(outputStreamInfo->flags & paWinWasapiPolling))
4039 ||
4040 (!(inputStreamInfo->flags & paWinWasapiPolling) &&
4041 (outputStreamInfo->flags & paWinWasapiPolling)))
4042 {
4043 LogPaError(result = paInvalidFlag);
4044 goto error;
4045 }
4046 }
4047 }
4048
4049 // Initialize stream representation
4050 if (streamCallback)
4051 {
4052 stream->bBlocking = FALSE;
4053 PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
4054 &paWasapi->callbackStreamInterface,
4055 streamCallback, userData);
4056 }
4057 else
4058 {
4059 stream->bBlocking = TRUE;
4060 PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
4061 &paWasapi->blockingStreamInterface,
4062 streamCallback, userData);
4063 }
4064
4065 // Initialize CPU measurer
4066 PaUtil_InitializeCpuLoadMeasurer(&stream->cpuLoadMeasurer, sampleRate);
4067
4068 if (outputParameters && inputParameters)
4069 {
4070 // serious problem #1 - No, Not a problem, especially concerning Exclusive mode.
4071 // Input device in exclusive mode somehow is getting large buffer always, thus we
4072 // adjust Output latency to reflect it, thus period will differ but playback will be
4073 // normal.
4074 /*if (stream->in.period != stream->out.period)
4075 {
4076 PRINT(("WASAPI: OpenStream: period discrepancy\n"));
4077 LogPaError(result = paBadIODeviceCombination);
4078 goto error;
4079 }*/
4080
4081 // serious problem #2 - No, Not a problem, as framesPerHostCallback take into account
4082 // sample size while it is not a problem for PA full-duplex, we must care of
4083 // period only!
4084 /*if (stream->out.framesPerHostCallback != stream->in.framesPerHostCallback)
4085 {
4086 PRINT(("WASAPI: OpenStream: framesPerHostCallback discrepancy\n"));
4087 goto error;
4088 }*/
4089 }
4090
4091 // Calculate frames per host for processor
4092 framesPerHostCallback = (outputParameters ? stream->out.framesPerBuffer : stream->in.framesPerBuffer);
4093
4094 // Choose correct mode of buffer processing:
4095 // Exclusive/Shared non paWinWasapiPolling mode: paUtilFixedHostBufferSize - always fixed
4096 // Exclusive/Shared paWinWasapiPolling mode: paUtilBoundedHostBufferSize - may vary for Exclusive or Full-duplex
4097 bufferMode = paUtilFixedHostBufferSize;
4098 if (inputParameters) // !!! WASAPI IAudioCaptureClient::GetBuffer extracts not number of frames but 1 packet, thus we always must adapt
4099 bufferMode = paUtilBoundedHostBufferSize;
4100 else
4101 if (outputParameters)
4102 {
4103 if ((stream->out.buffers == 1) &&
4104 (!stream->out.streamFlags || ((stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
4105 bufferMode = paUtilBoundedHostBufferSize;
4106 }
4107 stream->bufferMode = bufferMode;
4108
4109 // Initialize buffer processor
4110 if (useInputBufferProcessor || useOutputBufferProcessor)
4111 {
4112 result = PaUtil_InitializeBufferProcessor(
4113 &stream->bufferProcessor,
4114 inputChannelCount,
4115 inputSampleFormat,
4116 hostInputSampleFormat,
4117 outputChannelCount,
4118 outputSampleFormat,
4119 hostOutputSampleFormat,
4120 sampleRate,
4121 streamFlags,
4122 framesPerBuffer,
4123 framesPerHostCallback,
4124 bufferMode,
4125 streamCallback,
4126 userData);
4127 if (result != paNoError)
4128 {
4129 LogPaError(result);
4130 goto error;
4131 }
4132 }
4133
4134 // Set Input latency
4135 stream->streamRepresentation.streamInfo.inputLatency =
4136 (useInputBufferProcessor ? PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor) / sampleRate : 0)
4137 + (inputParameters != NULL ? stream->in.latencySeconds : 0);
4138
4139 // Set Output latency
4140 stream->streamRepresentation.streamInfo.outputLatency =
4141 (useOutputBufferProcessor ? PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor) / sampleRate : 0)
4142 + (outputParameters != NULL ? stream->out.latencySeconds : 0);
4143
4144 // Set SR
4145 stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
4146
4147 (*s) = (PaStream *)stream;
4148 return result;
4149
4150 error:
4151
4152 if (stream != NULL)
4153 CloseStream(stream);
4154
4155 return result;
4156 }
4157
4158 // ------------------------------------------------------------------------------------------
4159 static PaError CloseStream( PaStream* s )
4160 {
4161 PaError result = paNoError;
4162 PaWasapiStream *stream = (PaWasapiStream*)s;
4163
4164 // abort active stream
4165 if (IsStreamActive(s))
4166 {
4167 result = AbortStream(s);
4168 }
4169
4170 SAFE_RELEASE(stream->captureClientParent);
4171 SAFE_RELEASE(stream->renderClientParent);
4172 SAFE_RELEASE(stream->out.clientParent);
4173 SAFE_RELEASE(stream->in.clientParent);
4174 SAFE_RELEASE(stream->inVol);
4175 SAFE_RELEASE(stream->outVol);
4176
4177 CloseHandle(stream->event[S_INPUT]);
4178 CloseHandle(stream->event[S_OUTPUT]);
4179
4180 _StreamCleanup(stream);
4181
4182 PaWasapi_FreeMemory(stream->in.monoBuffer);
4183 PaWasapi_FreeMemory(stream->out.monoBuffer);
4184
4185 PaUtil_FreeMemory(stream->in.tailBuffer);
4186 PaUtil_FreeMemory(stream->in.tailBufferMemory);
4187
4188 PaUtil_FreeMemory(stream->out.tailBuffer);
4189 PaUtil_FreeMemory(stream->out.tailBufferMemory);
4190
4191 PaUtil_TerminateBufferProcessor(&stream->bufferProcessor);
4192 PaUtil_TerminateStreamRepresentation(&stream->streamRepresentation);
4193 PaUtil_FreeMemory(stream);
4194
4195 return result;
4196 }
4197
4198 // ------------------------------------------------------------------------------------------
4199 HRESULT UnmarshalSubStreamComPointers(PaWasapiSubStream *substream)
4200 {
4201 #ifndef PA_WINRT
4202 HRESULT hResult = S_OK;
4203 HRESULT hFirstBadResult = S_OK;
4204 substream->clientProc = NULL;
4205
4206 // IAudioClient
4207 hResult = CoGetInterfaceAndReleaseStream(substream->clientStream, GetAudioClientIID(), (LPVOID*)&substream->clientProc);
4208 substream->clientStream = NULL;
4209 if (hResult != S_OK)
4210 {
4211 hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
4212 }
4213
4214 return hFirstBadResult;
4215
4216 #else
4217 (void)substream;
4218 return S_OK;
4219 #endif
4220 }
4221
4222 // ------------------------------------------------------------------------------------------
4223 HRESULT UnmarshalStreamComPointers(PaWasapiStream *stream)
4224 {
4225 #ifndef PA_WINRT
4226 HRESULT hResult = S_OK;
4227 HRESULT hFirstBadResult = S_OK;
4228 stream->captureClient = NULL;
4229 stream->renderClient = NULL;
4230 stream->in.clientProc = NULL;
4231 stream->out.clientProc = NULL;
4232
4233 if (NULL != stream->in.clientParent)
4234 {
4235 // SubStream pointers
4236 hResult = UnmarshalSubStreamComPointers(&stream->in);
4237 if (hResult != S_OK)
4238 {
4239 hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
4240 }
4241
4242 // IAudioCaptureClient
4243 hResult = CoGetInterfaceAndReleaseStream(stream->captureClientStream, &pa_IID_IAudioCaptureClient, (LPVOID*)&stream->captureClient);
4244 stream->captureClientStream = NULL;
4245 if (hResult != S_OK)
4246 {
4247 hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
4248 }
4249 }
4250
4251 if (NULL != stream->out.clientParent)
4252 {
4253 // SubStream pointers
4254 hResult = UnmarshalSubStreamComPointers(&stream->out);
4255 if (hResult != S_OK)
4256 {
4257 hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
4258 }
4259
4260 // IAudioRenderClient
4261 hResult = CoGetInterfaceAndReleaseStream(stream->renderClientStream, &pa_IID_IAudioRenderClient, (LPVOID*)&stream->renderClient);
4262 stream->renderClientStream = NULL;
4263 if (hResult != S_OK)
4264 {
4265 hFirstBadResult = (hFirstBadResult == S_OK) ? hResult : hFirstBadResult;
4266 }
4267 }
4268
4269 return hFirstBadResult;
4270 #else
4271 if (stream->in.clientParent != NULL)
4272 {
4273 stream->in.clientProc = stream->in.clientParent;
4274 IAudioClient_AddRef(stream->in.clientParent);
4275 }
4276
4277 if (stream->out.clientParent != NULL)
4278 {
4279 stream->out.clientProc = stream->out.clientParent;
4280 IAudioClient_AddRef(stream->out.clientParent);
4281 }
4282
4283 if (stream->renderClientParent != NULL)
4284 {
4285 stream->renderClient = stream->renderClientParent;
4286 IAudioRenderClient_AddRef(stream->renderClientParent);
4287 }
4288
4289 if (stream->captureClientParent != NULL)
4290 {
4291 stream->captureClient = stream->captureClientParent;
4292 IAudioCaptureClient_AddRef(stream->captureClientParent);
4293 }
4294
4295 return S_OK;
4296 #endif
4297 }
4298
4299 // -----------------------------------------------------------------------------------------
4300 void ReleaseUnmarshaledSubComPointers(PaWasapiSubStream *substream)
4301 {
4302 SAFE_RELEASE(substream->clientProc);
4303 }
4304
4305 // -----------------------------------------------------------------------------------------
4306 void ReleaseUnmarshaledComPointers(PaWasapiStream *stream)
4307 {
4308 // Release AudioClient services first
4309 SAFE_RELEASE(stream->captureClient);
4310 SAFE_RELEASE(stream->renderClient);
4311
4312 // Release AudioClients
4313 ReleaseUnmarshaledSubComPointers(&stream->in);
4314 ReleaseUnmarshaledSubComPointers(&stream->out);
4315 }
4316
4317 // ------------------------------------------------------------------------------------------
4318 HRESULT MarshalSubStreamComPointers(PaWasapiSubStream *substream)
4319 {
4320 #ifndef PA_WINRT
4321 HRESULT hResult;
4322 substream->clientStream = NULL;
4323
4324 // IAudioClient
4325 hResult = CoMarshalInterThreadInterfaceInStream(GetAudioClientIID(), (LPUNKNOWN)substream->clientParent, &substream->clientStream);
4326 if (hResult != S_OK)
4327 goto marshal_sub_error;
4328
4329 return hResult;
4330
4331 // If marshaling error occurred, make sure to release everything.
4332 marshal_sub_error:
4333
4334 UnmarshalSubStreamComPointers(substream);
4335 ReleaseUnmarshaledSubComPointers(substream);
4336 return hResult;
4337 #else
4338 (void)substream;
4339 return S_OK;
4340 #endif
4341 }
4342
4343 // ------------------------------------------------------------------------------------------
4344 HRESULT MarshalStreamComPointers(PaWasapiStream *stream)
4345 {
4346 #ifndef PA_WINRT
4347 HRESULT hResult = S_OK;
4348 stream->captureClientStream = NULL;
4349 stream->in.clientStream = NULL;
4350 stream->renderClientStream = NULL;
4351 stream->out.clientStream = NULL;
4352
4353 if (NULL != stream->in.clientParent)
4354 {
4355 // SubStream pointers
4356 hResult = MarshalSubStreamComPointers(&stream->in);
4357 if (hResult != S_OK)
4358 goto marshal_error;
4359
4360 // IAudioCaptureClient
4361 hResult = CoMarshalInterThreadInterfaceInStream(&pa_IID_IAudioCaptureClient, (LPUNKNOWN)stream->captureClientParent, &stream->captureClientStream);
4362 if (hResult != S_OK)
4363 goto marshal_error;
4364 }
4365
4366 if (NULL != stream->out.clientParent)
4367 {
4368 // SubStream pointers
4369 hResult = MarshalSubStreamComPointers(&stream->out);
4370 if (hResult != S_OK)
4371 goto marshal_error;
4372
4373 // IAudioRenderClient
4374 hResult = CoMarshalInterThreadInterfaceInStream(&pa_IID_IAudioRenderClient, (LPUNKNOWN)stream->renderClientParent, &stream->renderClientStream);
4375 if (hResult != S_OK)
4376 goto marshal_error;
4377 }
4378
4379 return hResult;
4380
4381 // If marshaling error occurred, make sure to release everything.
4382 marshal_error:
4383
4384 UnmarshalStreamComPointers(stream);
4385 ReleaseUnmarshaledComPointers(stream);
4386 return hResult;
4387 #else
4388 (void)stream;
4389 return S_OK;
4390 #endif
4391 }
4392
4393 // ------------------------------------------------------------------------------------------
4394 static PaError StartStream( PaStream *s )
4395 {
4396 HRESULT hr;
4397 PaWasapiStream *stream = (PaWasapiStream*)s;
4398 PaError result = paNoError;
4399
4400 // check if stream is active already
4401 if (IsStreamActive(s))
4402 return paStreamIsNotStopped;
4403
4404 PaUtil_ResetBufferProcessor(&stream->bufferProcessor);
4405
4406 // Cleanup handles (may be necessary if stream was stopped by itself due to error)
4407 _StreamCleanup(stream);
4408
4409 // Create close event
4410 if ((stream->hCloseRequest = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL)
4411 {
4412 result = paInsufficientMemory;
4413 goto start_error;
4414 }
4415
4416 // Create thread
4417 if (!stream->bBlocking)
4418 {
4419 // Create thread events
4420 stream->hThreadStart = CreateEvent(NULL, TRUE, FALSE, NULL);
4421 stream->hThreadExit = CreateEvent(NULL, TRUE, FALSE, NULL);
4422 if ((stream->hThreadStart == NULL) || (stream->hThreadExit == NULL))
4423 {
4424 result = paInsufficientMemory;
4425 goto start_error;
4426 }
4427
4428 // Marshal WASAPI interface pointers for safe use in thread created below.
4429 if ((hr = MarshalStreamComPointers(stream)) != S_OK)
4430 {
4431 PRINT(("Failed marshaling stream COM pointers."));
4432 result = paUnanticipatedHostError;
4433 goto nonblocking_start_error;
4434 }
4435
4436 if ((stream->in.clientParent && (stream->in.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)) ||
4437 (stream->out.clientParent && (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)))
4438 {
4439 if ((stream->hThread = CREATE_THREAD(ProcThreadEvent)) == NULL)
4440 {
4441 PRINT(("Failed creating thread: ProcThreadEvent."));
4442 result = paUnanticipatedHostError;
4443 goto nonblocking_start_error;
4444 }
4445 }
4446 else
4447 {
4448 if ((stream->hThread = CREATE_THREAD(ProcThreadPoll)) == NULL)
4449 {
4450 PRINT(("Failed creating thread: ProcThreadPoll."));
4451 result = paUnanticipatedHostError;
4452 goto nonblocking_start_error;
4453 }
4454 }
4455
4456 // Wait for thread to start
4457 if (WaitForSingleObject(stream->hThreadStart, 60*1000) == WAIT_TIMEOUT)
4458 {
4459 PRINT(("Failed starting thread: timeout."));
4460 result = paUnanticipatedHostError;
4461 goto nonblocking_start_error;
4462 }
4463 }
4464 else
4465 {
4466 // Create blocking operation events (non-signaled event means - blocking operation is pending)
4467 if (stream->out.clientParent != NULL)
4468 {
4469 if ((stream->hBlockingOpStreamWR = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL)
4470 {
4471 result = paInsufficientMemory;
4472 goto start_error;
4473 }
4474 }
4475 if (stream->in.clientParent != NULL)
4476 {
4477 if ((stream->hBlockingOpStreamRD = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL)
4478 {
4479 result = paInsufficientMemory;
4480 goto start_error;
4481 }
4482 }
4483
4484 // Initialize event & start INPUT stream
4485 if (stream->in.clientParent != NULL)
4486 {
4487 if ((hr = IAudioClient_Start(stream->in.clientParent)) != S_OK)
4488 {
4489 LogHostError(hr);
4490 result = paUnanticipatedHostError;
4491 goto start_error;
4492 }
4493 }
4494
4495 // Initialize event & start OUTPUT stream
4496 if (stream->out.clientParent != NULL)
4497 {
4498 // Start
4499 if ((hr = IAudioClient_Start(stream->out.clientParent)) != S_OK)
4500 {
4501 LogHostError(hr);
4502 result = paUnanticipatedHostError;
4503 goto start_error;
4504 }
4505 }
4506
4507 // Set parent to working pointers to use shared functions.
4508 stream->captureClient = stream->captureClientParent;
4509 stream->renderClient = stream->renderClientParent;
4510 stream->in.clientProc = stream->in.clientParent;
4511 stream->out.clientProc = stream->out.clientParent;
4512
4513 // Signal: stream running.
4514 stream->running = TRUE;
4515 }
4516
4517 return result;
4518
4519 nonblocking_start_error:
4520
4521 // Set hThreadExit event to prevent blocking during cleanup
4522 SetEvent(stream->hThreadExit);
4523 UnmarshalStreamComPointers(stream);
4524 ReleaseUnmarshaledComPointers(stream);
4525
4526 start_error:
4527
4528 StopStream(s);
4529 return result;
4530 }
4531
4532 // ------------------------------------------------------------------------------------------
4533 void _StreamFinish(PaWasapiStream *stream)
4534 {
4535 // Issue command to thread to stop processing and wait for thread exit
4536 if (!stream->bBlocking)
4537 {
4538 SignalObjectAndWait(stream->hCloseRequest, stream->hThreadExit, INFINITE, FALSE);
4539 }
4540 else
4541 // Blocking mode does not own thread
4542 {
4543 // Signal close event and wait for each of 2 blocking operations to complete
4544 if (stream->out.clientParent)
4545 SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamWR, INFINITE, TRUE);
4546 if (stream->out.clientParent)
4547 SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamRD, INFINITE, TRUE);
4548
4549 // Process stop
4550 _StreamOnStop(stream);
4551 }
4552
4553 // Cleanup handles
4554 _StreamCleanup(stream);
4555
4556 stream->running = FALSE;
4557 }
4558
4559 // ------------------------------------------------------------------------------------------
4560 void _StreamCleanup(PaWasapiStream *stream)
4561 {
4562 // Close thread handles to allow restart
4563 SAFE_CLOSE(stream->hThread);
4564 SAFE_CLOSE(stream->hThreadStart);
4565 SAFE_CLOSE(stream->hThreadExit);
4566 SAFE_CLOSE(stream->hCloseRequest);
4567 SAFE_CLOSE(stream->hBlockingOpStreamRD);
4568 SAFE_CLOSE(stream->hBlockingOpStreamWR);
4569 }
4570
4571 // ------------------------------------------------------------------------------------------
4572 static PaError StopStream( PaStream *s )
4573 {
4574 // Finish stream
4575 _StreamFinish((PaWasapiStream *)s);
4576 return paNoError;
4577 }
4578
4579 // ------------------------------------------------------------------------------------------
4580 static PaError AbortStream( PaStream *s )
4581 {
4582 // Finish stream
4583 _StreamFinish((PaWasapiStream *)s);
4584 return paNoError;
4585 }
4586
4587 // ------------------------------------------------------------------------------------------
4588 static PaError IsStreamStopped( PaStream *s )
4589 {
4590 return !((PaWasapiStream *)s)->running;
4591 }
4592
4593 // ------------------------------------------------------------------------------------------
4594 static PaError IsStreamActive( PaStream *s )
4595 {
4596 return ((PaWasapiStream *)s)->running;
4597 }
4598
4599 // ------------------------------------------------------------------------------------------
4600 static PaTime GetStreamTime( PaStream *s )
4601 {
4602 PaWasapiStream *stream = (PaWasapiStream*)s;
4603
4604 /* suppress unused variable warnings */
4605 (void) stream;
4606
4607 return PaUtil_GetTime();
4608 }
4609
4610 // ------------------------------------------------------------------------------------------
4611 static double GetStreamCpuLoad( PaStream* s )
4612 {
4613 return PaUtil_GetCpuLoad(&((PaWasapiStream *)s)->cpuLoadMeasurer);
4614 }
4615
4616 // ------------------------------------------------------------------------------------------
4617 static PaError ReadStream( PaStream* s, void *_buffer, unsigned long frames )
4618 {
4619 PaWasapiStream *stream = (PaWasapiStream*)s;
4620
4621 HRESULT hr = S_OK;
4622 BYTE *user_buffer = (BYTE *)_buffer;
4623 BYTE *wasapi_buffer = NULL;
4624 DWORD flags = 0;
4625 UINT32 i, available, sleep = 0;
4626 unsigned long processed;
4627 ThreadIdleScheduler sched;
4628
4629 // validate
4630 if (!stream->running)
4631 return paStreamIsStopped;
4632 if (stream->captureClient == NULL)
4633 return paBadStreamPtr;
4634
4635 // Notify blocking op has begun
4636 ResetEvent(stream->hBlockingOpStreamRD);
4637
4638 // Use thread scheduling for 500 microseconds (emulated) when wait time for frames is less than
4639 // 1 milliseconds, emulation helps to normalize CPU consumption and avoids too busy waiting
4640 ThreadIdleScheduler_Setup(&sched, 1, 250/* microseconds */);
4641
4642 // Make a local copy of the user buffer pointer(s), this is necessary
4643 // because PaUtil_CopyOutput() advances these pointers every time it is called
4644 if (!stream->bufferProcessor.userInputIsInterleaved)
4645 {
4646 user_buffer = (BYTE *)alloca(sizeof(BYTE *) * stream->bufferProcessor.inputChannelCount);
4647 if (user_buffer == NULL)
4648 return paInsufficientMemory;
4649
4650 for (i = 0; i < stream->bufferProcessor.inputChannelCount; ++i)
4651 ((BYTE **)user_buffer)[i] = ((BYTE **)_buffer)[i];
4652 }
4653
4654 // Find out if there are tail frames, flush them all before reading hardware
4655 if ((available = PaUtil_GetRingBufferReadAvailable(stream->in.tailBuffer)) != 0)
4656 {
4657 ring_buffer_size_t buf1_size = 0, buf2_size = 0, read, desired;
4658 void *buf1 = NULL, *buf2 = NULL;
4659
4660 // Limit desired to amount of requested frames
4661 desired = available;
4662 if ((UINT32)desired > frames)
4663 desired = frames;
4664
4665 // Get pointers to read regions
4666 read = PaUtil_GetRingBufferReadRegions(stream->in.tailBuffer, desired, &buf1, &buf1_size, &buf2, &buf2_size);
4667
4668 if (buf1 != NULL)
4669 {
4670 // Register available frames to processor
4671 PaUtil_SetInputFrameCount(&stream->bufferProcessor, buf1_size);
4672
4673 // Register host buffer pointer to processor
4674 PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, buf1, stream->bufferProcessor.inputChannelCount);
4675
4676 // Copy user data to host buffer (with conversion if applicable)
4677 processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, buf1_size);
4678 frames -= processed;
4679 }
4680
4681 if (buf2 != NULL)
4682 {
4683 // Register available frames to processor
4684 PaUtil_SetInputFrameCount(&stream->bufferProcessor, buf2_size);
4685
4686 // Register host buffer pointer to processor
4687 PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, buf2, stream->bufferProcessor.inputChannelCount);
4688
4689 // Copy user data to host buffer (with conversion if applicable)
4690 processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, buf2_size);
4691 frames -= processed;
4692 }
4693
4694 // Advance
4695 PaUtil_AdvanceRingBufferReadIndex(stream->in.tailBuffer, read);
4696 }
4697
4698 // Read hardware
4699 while (frames != 0)
4700 {
4701 // Check if blocking call must be interrupted
4702 if (WaitForSingleObject(stream->hCloseRequest, sleep) != WAIT_TIMEOUT)
4703 break;
4704
4705 // Get available frames (must be finding out available frames before call to IAudioCaptureClient_GetBuffer
4706 // othervise audio glitches will occur inExclusive mode as it seems that WASAPI has some scheduling/
4707 // processing problems when such busy polling with IAudioCaptureClient_GetBuffer occurs)
4708 if ((hr = _PollGetInputFramesAvailable(stream, &available)) != S_OK)
4709 {
4710 LogHostError(hr);
4711 return paUnanticipatedHostError;
4712 }
4713
4714 // Wait for more frames to become available
4715 if (available == 0)
4716 {
4717 // Exclusive mode may require latency of 1 millisecond, thus we shall sleep
4718 // around 500 microseconds (emulated) to collect packets in time
4719 if (stream->in.shareMode != AUDCLNT_SHAREMODE_EXCLUSIVE)
4720 {
4721 UINT32 sleep_frames = (frames < stream->in.framesPerHostCallback ? frames : stream->in.framesPerHostCallback);
4722
4723 sleep = GetFramesSleepTime(sleep_frames, stream->in.wavex.Format.nSamplesPerSec);
4724 sleep /= 4; // wait only for 1/4 of the buffer
4725
4726 // WASAPI input provides packets, thus expiring packet will result in bad audio
4727 // limit waiting time to 2 seconds (will always work for smallest buffer in Shared)
4728 if (sleep > 2)
4729 sleep = 2;
4730
4731 // Avoid busy waiting, schedule next 1 millesecond wait
4732 if (sleep == 0)
4733 sleep = ThreadIdleScheduler_NextSleep(&sched);
4734 }
4735 else
4736 {
4737 if ((sleep = ThreadIdleScheduler_NextSleep(&sched)) != 0)
4738 {
4739 Sleep(sleep);
4740 sleep = 0;
4741 }
4742 }
4743
4744 continue;
4745 }
4746
4747 // Get the available data in the shared buffer.
4748 if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &wasapi_buffer, &available, &flags, NULL, NULL)) != S_OK)
4749 {
4750 // Buffer size is too small, waiting
4751 if (hr != AUDCLNT_S_BUFFER_EMPTY)
4752 {
4753 LogHostError(hr);
4754 goto end;
4755 }
4756
4757 continue;
4758 }
4759
4760 // Register available frames to processor
4761 PaUtil_SetInputFrameCount(&stream->bufferProcessor, available);
4762
4763 // Register host buffer pointer to processor
4764 PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, wasapi_buffer, stream->bufferProcessor.inputChannelCount);
4765
4766 // Copy user data to host buffer (with conversion if applicable)
4767 processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, frames);
4768 frames -= processed;
4769
4770 // Save tail into buffer
4771 if ((frames == 0) && (available > processed))
4772 {
4773 UINT32 bytes_processed = processed * stream->in.wavex.Format.nBlockAlign;
4774 UINT32 frames_to_save = available - processed;
4775
4776 PaUtil_WriteRingBuffer(stream->in.tailBuffer, wasapi_buffer + bytes_processed, frames_to_save);
4777 }
4778
4779 // Release host buffer
4780 if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, available)) != S_OK)
4781 {
4782 LogHostError(hr);
4783 goto end;
4784 }
4785 }
4786
4787 end:
4788
4789 // Notify blocking op has ended
4790 SetEvent(stream->hBlockingOpStreamRD);
4791
4792 return (hr != S_OK ? paUnanticipatedHostError : paNoError);
4793 }
4794
4795 // ------------------------------------------------------------------------------------------
4796 static PaError WriteStream( PaStream* s, const void *_buffer, unsigned long frames )
4797 {
4798 PaWasapiStream *stream = (PaWasapiStream*)s;
4799
4800 //UINT32 frames;
4801 const BYTE *user_buffer = (const BYTE *)_buffer;
4802 BYTE *wasapi_buffer;
4803 HRESULT hr = S_OK;
4804 UINT32 i, available, sleep = 0;
4805 unsigned long processed;
4806 ThreadIdleScheduler sched;
4807
4808 // validate
4809 if (!stream->running)
4810 return paStreamIsStopped;
4811 if (stream->renderClient == NULL)
4812 return paBadStreamPtr;
4813
4814 // Notify blocking op has begun
4815 ResetEvent(stream->hBlockingOpStreamWR);
4816
4817 // Use thread scheduling for 500 microseconds (emulated) when wait time for frames is less than
4818 // 1 milliseconds, emulation helps to normalize CPU consumption and avoids too busy waiting
4819 ThreadIdleScheduler_Setup(&sched, 1, 500/* microseconds */);
4820
4821 // Make a local copy of the user buffer pointer(s), this is necessary
4822 // because PaUtil_CopyOutput() advances these pointers every time it is called
4823 if (!stream->bufferProcessor.userOutputIsInterleaved)
4824 {
4825 user_buffer = (const BYTE *)alloca(sizeof(const BYTE *) * stream->bufferProcessor.outputChannelCount);
4826 if (user_buffer == NULL)
4827 return paInsufficientMemory;
4828
4829 for (i = 0; i < stream->bufferProcessor.outputChannelCount; ++i)
4830 ((const BYTE **)user_buffer)[i] = ((const BYTE **)_buffer)[i];
4831 }
4832
4833 // Blocking (potentially, until 'frames' are consumed) loop
4834 while (frames != 0)
4835 {
4836 // Check if blocking call must be interrupted
4837 if (WaitForSingleObject(stream->hCloseRequest, sleep) != WAIT_TIMEOUT)
4838 break;
4839
4840 // Get frames available
4841 if ((hr = _PollGetOutputFramesAvailable(stream, &available)) != S_OK)
4842 {
4843 LogHostError(hr);
4844 goto end;
4845 }
4846
4847 // Wait for more frames to become available
4848 if (available == 0)
4849 {
4850 UINT32 sleep_frames = (frames < stream->out.framesPerHostCallback ? frames : stream->out.framesPerHostCallback);
4851
4852 sleep = GetFramesSleepTime(sleep_frames, stream->out.wavex.Format.nSamplesPerSec);
4853 sleep /= 2; // wait only for half of the buffer
4854
4855 // Avoid busy waiting, schedule next 1 millesecond wait
4856 if (sleep == 0)
4857 sleep = ThreadIdleScheduler_NextSleep(&sched);
4858
4859 continue;
4860 }
4861
4862 // Keep in 'frames' range
4863 if (available > frames)
4864 available = frames;
4865
4866 // Get pointer to host buffer
4867 if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, available, &wasapi_buffer)) != S_OK)
4868 {
4869 // Buffer size is too big, waiting
4870 if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
4871 continue;
4872
4873 LogHostError(hr);
4874 goto end;
4875 }
4876
4877 // Keep waiting again (on Vista it was noticed that WASAPI could SOMETIMES return NULL pointer
4878 // to buffer without returning AUDCLNT_E_BUFFER_TOO_LARGE instead)
4879 if (wasapi_buffer == NULL)
4880 continue;
4881
4882 // Register available frames to processor
4883 PaUtil_SetOutputFrameCount(&stream->bufferProcessor, available);
4884
4885 // Register host buffer pointer to processor
4886 PaUtil_SetInterleavedOutputChannels(&stream->bufferProcessor, 0, wasapi_buffer, stream->bufferProcessor.outputChannelCount);
4887
4888 // Copy user data to host buffer (with conversion if applicable), this call will advance
4889 // pointer 'user_buffer' to consumed portion of data
4890 processed = PaUtil_CopyOutput(&stream->bufferProcessor, (const void **)&user_buffer, frames);
4891 frames -= processed;
4892
4893 // Release host buffer
4894 if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, available, 0)) != S_OK)
4895 {
4896 LogHostError(hr);
4897 goto end;
4898 }
4899 }
4900
4901 end:
4902
4903 // Notify blocking op has ended
4904 SetEvent(stream->hBlockingOpStreamWR);
4905
4906 return (hr != S_OK ? paUnanticipatedHostError : paNoError);
4907 }
4908
4909 unsigned long PaUtil_GetOutputFrameCount( PaUtilBufferProcessor* bp )
4910 {
4911 return bp->hostOutputFrameCount[0];
4912 }
4913
4914 // ------------------------------------------------------------------------------------------
4915 static signed long GetStreamReadAvailable( PaStream* s )
4916 {
4917 PaWasapiStream *stream = (PaWasapiStream*)s;
4918
4919 HRESULT hr;
4920 UINT32 available = 0;
4921
4922 // validate
4923 if (!stream->running)
4924 return paStreamIsStopped;
4925 if (stream->captureClient == NULL)
4926 return paBadStreamPtr;
4927
4928 // available in hardware buffer
4929 if ((hr = _PollGetInputFramesAvailable(stream, &available)) != S_OK)
4930 {
4931 LogHostError(hr);
4932 return paUnanticipatedHostError;
4933 }
4934
4935 // available in software tail buffer
4936 available += PaUtil_GetRingBufferReadAvailable(stream->in.tailBuffer);
4937
4938 return available;
4939 }
4940
4941 // ------------------------------------------------------------------------------------------
4942 static signed long GetStreamWriteAvailable( PaStream* s )
4943 {
4944 PaWasapiStream *stream = (PaWasapiStream*)s;
4945 HRESULT hr;
4946 UINT32 available = 0;
4947
4948 // validate
4949 if (!stream->running)
4950 return paStreamIsStopped;
4951 if (stream->renderClient == NULL)
4952 return paBadStreamPtr;
4953
4954 if ((hr = _PollGetOutputFramesAvailable(stream, &available)) != S_OK)
4955 {
4956 LogHostError(hr);
4957 return paUnanticipatedHostError;
4958 }
4959
4960 return (signed long)available;
4961 }
4962
4963
4964 // ------------------------------------------------------------------------------------------
4965 static void WaspiHostProcessingLoop( void *inputBuffer, long inputFrames,
4966 void *outputBuffer, long outputFrames,
4967 void *userData )
4968 {
4969 PaWasapiStream *stream = (PaWasapiStream*)userData;
4970 PaStreamCallbackTimeInfo timeInfo = {0,0,0};
4971 PaStreamCallbackFlags flags = 0;
4972 int callbackResult;
4973 unsigned long framesProcessed;
4974 HRESULT hr;
4975 UINT32 pending;
4976
4977 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
4978
4979 /*
4980 Pa_GetStreamTime:
4981 - generate timing information
4982 - handle buffer slips
4983 */
4984 timeInfo.currentTime = PaUtil_GetTime();
4985 // Query input latency
4986 if (stream->in.clientProc != NULL)
4987 {
4988 PaTime pending_time;
4989 if ((hr = IAudioClient_GetCurrentPadding(stream->in.clientProc, &pending)) == S_OK)
4990 pending_time = (PaTime)pending / (PaTime)stream->in.wavex.Format.nSamplesPerSec;
4991 else
4992 pending_time = (PaTime)stream->in.latencySeconds;
4993
4994 timeInfo.inputBufferAdcTime = timeInfo.currentTime + pending_time;
4995 }
4996 // Query output current latency
4997 if (stream->out.clientProc != NULL)
4998 {
4999 PaTime pending_time;
5000 if ((hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &pending)) == S_OK)
5001 pending_time = (PaTime)pending / (PaTime)stream->out.wavex.Format.nSamplesPerSec;
5002 else
5003 pending_time = (PaTime)stream->out.latencySeconds;
5004
5005 timeInfo.outputBufferDacTime = timeInfo.currentTime + pending_time;
5006 }
5007
5008 /*
5009 If you need to byte swap or shift inputBuffer to convert it into a
5010 portaudio format, do it here.
5011 */
5012
5013 PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, flags );
5014
5015 /*
5016 depending on whether the host buffers are interleaved, non-interleaved
5017 or a mixture, you will want to call PaUtil_SetInterleaved*Channels(),
5018 PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here.
5019 */
5020
5021 if (stream->bufferProcessor.inputChannelCount > 0)
5022 {
5023 PaUtil_SetInputFrameCount( &stream->bufferProcessor, inputFrames );
5024 PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor,
5025 0, /* first channel of inputBuffer is channel 0 */
5026 inputBuffer,
5027 0 ); /* 0 - use inputChannelCount passed to init buffer processor */
5028 }
5029
5030 if (stream->bufferProcessor.outputChannelCount > 0)
5031 {
5032 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, outputFrames);
5033 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor,
5034 0, /* first channel of outputBuffer is channel 0 */
5035 outputBuffer,
5036 0 ); /* 0 - use outputChannelCount passed to init buffer processor */
5037 }
5038
5039 /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing()
5040 in general you would pass paContinue for normal operation, and
5041 paComplete to drain the buffer processor's internal output buffer.
5042 You can check whether the buffer processor's output buffer is empty
5043 using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor )
5044 */
5045 callbackResult = paContinue;
5046 framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
5047
5048 /*
5049 If you need to byte swap or shift outputBuffer to convert it to
5050 host format, do it here.
5051 */
5052
5053 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
5054
5055 if (callbackResult == paContinue)
5056 {
5057 /* nothing special to do */
5058 }
5059 else
5060 if (callbackResult == paAbort)
5061 {
5062 // stop stream
5063 SetEvent(stream->hCloseRequest);
5064 }
5065 else
5066 {
5067 // stop stream
5068 SetEvent(stream->hCloseRequest);
5069 }
5070 }
5071
5072 // ------------------------------------------------------------------------------------------
5073 #ifndef PA_WINRT
5074 static PaError MMCSS_activate(PaWasapiThreadPriority nPriorityClass, HANDLE *ret)
5075 {
5076 static const char *mmcs_name[] =
5077 {
5078 NULL,
5079 "Audio",
5080 "Capture",
5081 "Distribution",
5082 "Games",
5083 "Playback",
5084 "Pro Audio",
5085 "Window Manager"
5086 };
5087
5088 DWORD task_idx = 0;
5089 HANDLE hTask;
5090
5091 if ((UINT32)nPriorityClass >= STATIC_ARRAY_SIZE(mmcs_name))
5092 return paUnanticipatedHostError;
5093
5094 if ((hTask = pAvSetMmThreadCharacteristics(mmcs_name[nPriorityClass], &task_idx)) == NULL)
5095 {
5096 PRINT(("WASAPI: AvSetMmThreadCharacteristics failed: error[%d]\n", GetLastError()));
5097 return paUnanticipatedHostError;
5098 }
5099
5100 /*BOOL priority_ok = pAvSetMmThreadPriority(hTask, AVRT_PRIORITY_NORMAL);
5101 if (priority_ok == FALSE)
5102 {
5103 PRINT(("WASAPI: AvSetMmThreadPriority failed!\n"));
5104 }*/
5105
5106 // debug
5107 {
5108 int cur_priority = GetThreadPriority(GetCurrentThread());
5109 DWORD cur_priority_class = GetPriorityClass(GetCurrentProcess());
5110 PRINT(("WASAPI: thread[ priority-0x%X class-0x%X ]\n", cur_priority, cur_priority_class));
5111 }
5112
5113 (*ret) = hTask;
5114 return paNoError;
5115 }
5116 #endif
5117
5118 // ------------------------------------------------------------------------------------------
5119 #ifndef PA_WINRT
5120 static void MMCSS_deactivate(HANDLE hTask)
5121 {
5122 if (pAvRevertMmThreadCharacteristics(hTask) == FALSE)
5123 {
5124 PRINT(("WASAPI: AvRevertMmThreadCharacteristics failed!\n"));
5125 }
5126 }
5127 #endif
5128
5129 // ------------------------------------------------------------------------------------------
5130 PaError PaWasapi_ThreadPriorityBoost(void **pTask, PaWasapiThreadPriority priorityClass)
5131 {
5132 HANDLE task;
5133 PaError ret;
5134
5135 if (pTask == NULL)
5136 return paUnanticipatedHostError;
5137
5138 #ifndef PA_WINRT
5139 if ((ret = MMCSS_activate(priorityClass, &task)) != paNoError)
5140 return ret;
5141 #else
5142 switch (priorityClass)
5143 {
5144 case eThreadPriorityAudio:
5145 case eThreadPriorityProAudio: {
5146
5147 // Save previous thread priority
5148 intptr_t priority_prev = GetThreadPriority(GetCurrentThread());
5149
5150 // Try set new thread priority
5151 if (SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) == FALSE)
5152 return paUnanticipatedHostError;
5153
5154 // Memorize prev priority (pretend to be non NULL pointer by adding 0x80000000 mask)
5155 task = (HANDLE)(priority_prev | 0x80000000);
5156
5157 ret = paNoError;
5158
5159 break; }
5160
5161 default:
5162 return paUnanticipatedHostError;
5163 }
5164 #endif
5165
5166 (*pTask) = task;
5167 return ret;
5168 }
5169
5170 // ------------------------------------------------------------------------------------------
5171 PaError PaWasapi_ThreadPriorityRevert(void *pTask)
5172 {
5173 if (pTask == NULL)
5174 return paUnanticipatedHostError;
5175
5176 #ifndef PA_WINRT
5177 MMCSS_deactivate((HANDLE)pTask);
5178 #else
5179 // Revert previous priority by removing 0x80000000 mask
5180 if (SetThreadPriority(GetCurrentThread(), (int)((intptr_t)pTask & ~0x80000000)) == FALSE)
5181 return paUnanticipatedHostError;
5182 #endif
5183
5184 return paNoError;
5185 }
5186
5187 // ------------------------------------------------------------------------------------------
5188 // Described at:
5189 // http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
5190
5191 PaError PaWasapi_GetJackCount(PaDeviceIndex device, int *pJackCount)
5192 {
5193 #ifndef PA_WINRT
5194 PaError ret;
5195 HRESULT hr = S_OK;
5196 PaWasapiDeviceInfo *deviceInfo;
5197 IDeviceTopology *pDeviceTopology = NULL;
5198 IConnector *pConnFrom = NULL;
5199 IConnector *pConnTo = NULL;
5200 IPart *pPart = NULL;
5201 IKsJackDescription *pJackDesc = NULL;
5202 UINT jackCount = 0;
5203
5204 if (pJackCount == NULL)
5205 return paUnanticipatedHostError;
5206
5207 if ((ret = _GetWasapiDeviceInfoByDeviceIndex(&deviceInfo, device)) != paNoError)
5208 return ret;
5209
5210 // Get the endpoint device's IDeviceTopology interface
5211 hr = IMMDevice_Activate(deviceInfo->device, &pa_IID_IDeviceTopology,
5212 CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
5213 IF_FAILED_JUMP(hr, error);
5214
5215 // The device topology for an endpoint device always contains just one connector (connector number 0)
5216 hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
5217 IF_FAILED_JUMP(hr, error);
5218
5219 // Step across the connection to the jack on the adapter
5220 hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
5221 if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
5222 {
5223 // The adapter device is not currently active
5224 hr = E_NOINTERFACE;
5225 }
5226 IF_FAILED_JUMP(hr, error);
5227
5228 // Get the connector's IPart interface
5229 hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
5230 IF_FAILED_JUMP(hr, error);
5231
5232 // Activate the connector's IKsJackDescription interface
5233 hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
5234 IF_FAILED_JUMP(hr, error);
5235
5236 // Return jack count for this device
5237 hr = IKsJackDescription_GetJackCount(pJackDesc, &jackCount);
5238 IF_FAILED_JUMP(hr, error);
5239
5240 // Set.
5241 (*pJackCount) = jackCount;
5242
5243 // Ok.
5244 ret = paNoError;
5245
5246 error:
5247
5248 SAFE_RELEASE(pDeviceTopology);
5249 SAFE_RELEASE(pConnFrom);
5250 SAFE_RELEASE(pConnTo);
5251 SAFE_RELEASE(pPart);
5252 SAFE_RELEASE(pJackDesc);
5253
5254 LogHostError(hr);
5255 return paNoError;
5256 #else
5257 (void)device;
5258 (void)pJackCount;
5259 return paUnanticipatedHostError;
5260 #endif
5261 }
5262
5263 // ------------------------------------------------------------------------------------------
5264 #ifndef PA_WINRT
5265 static PaWasapiJackConnectionType _ConvertJackConnectionTypeWASAPIToPA(int connType)
5266 {
5267 switch (connType)
5268 {
5269 case eConnTypeUnknown: return eJackConnTypeUnknown;
5270 #ifdef _KS_
5271 case eConnType3Point5mm: return eJackConnType3Point5mm;
5272 #else
5273 case eConnTypeEighth: return eJackConnType3Point5mm;
5274 #endif
5275 case eConnTypeQuarter: return eJackConnTypeQuarter;
5276 case eConnTypeAtapiInternal: return eJackConnTypeAtapiInternal;
5277 case eConnTypeRCA: return eJackConnTypeRCA;
5278 case eConnTypeOptical: return eJackConnTypeOptical;
5279 case eConnTypeOtherDigital: return eJackConnTypeOtherDigital;
5280 case eConnTypeOtherAnalog: return eJackConnTypeOtherAnalog;
5281 case eConnTypeMultichannelAnalogDIN: return eJackConnTypeMultichannelAnalogDIN;
5282 case eConnTypeXlrProfessional: return eJackConnTypeXlrProfessional;
5283 case eConnTypeRJ11Modem: return eJackConnTypeRJ11Modem;
5284 case eConnTypeCombination: return eJackConnTypeCombination;
5285 }
5286 return eJackConnTypeUnknown;
5287 }
5288 #endif
5289
5290 // ------------------------------------------------------------------------------------------
5291 #ifndef PA_WINRT
5292 static PaWasapiJackGeoLocation _ConvertJackGeoLocationWASAPIToPA(int geoLoc)
5293 {
5294 switch (geoLoc)
5295 {
5296 case eGeoLocRear: return eJackGeoLocRear;
5297 case eGeoLocFront: return eJackGeoLocFront;
5298 case eGeoLocLeft: return eJackGeoLocLeft;
5299 case eGeoLocRight: return eJackGeoLocRight;
5300 case eGeoLocTop: return eJackGeoLocTop;
5301 case eGeoLocBottom: return eJackGeoLocBottom;
5302 #ifdef _KS_
5303 case eGeoLocRearPanel: return eJackGeoLocRearPanel;
5304 #else
5305 case eGeoLocRearOPanel: return eJackGeoLocRearPanel;
5306 #endif
5307 case eGeoLocRiser: return eJackGeoLocRiser;
5308 case eGeoLocInsideMobileLid: return eJackGeoLocInsideMobileLid;
5309 case eGeoLocDrivebay: return eJackGeoLocDrivebay;
5310 case eGeoLocHDMI: return eJackGeoLocHDMI;
5311 case eGeoLocOutsideMobileLid: return eJackGeoLocOutsideMobileLid;
5312 case eGeoLocATAPI: return eJackGeoLocATAPI;
5313 }
5314 return eJackGeoLocUnk;
5315 }
5316 #endif
5317
5318 // ------------------------------------------------------------------------------------------
5319 #ifndef PA_WINRT
5320 static PaWasapiJackGenLocation _ConvertJackGenLocationWASAPIToPA(int genLoc)
5321 {
5322 switch (genLoc)
5323 {
5324 case eGenLocPrimaryBox: return eJackGenLocPrimaryBox;
5325 case eGenLocInternal: return eJackGenLocInternal;
5326 #ifdef _KS_
5327 case eGenLocSeparate: return eJackGenLocSeparate;
5328 #else
5329 case eGenLocSeperate: return eJackGenLocSeparate;
5330 #endif
5331 case eGenLocOther: return eJackGenLocOther;
5332 }
5333 return eJackGenLocPrimaryBox;
5334 }
5335 #endif
5336
5337 // ------------------------------------------------------------------------------------------
5338 #ifndef PA_WINRT
5339 static PaWasapiJackPortConnection _ConvertJackPortConnectionWASAPIToPA(int portConn)
5340 {
5341 switch (portConn)
5342 {
5343 case ePortConnJack: return eJackPortConnJack;
5344 case ePortConnIntegratedDevice: return eJackPortConnIntegratedDevice;
5345 case ePortConnBothIntegratedAndJack: return eJackPortConnBothIntegratedAndJack;
5346 case ePortConnUnknown: return eJackPortConnUnknown;
5347 }
5348 return eJackPortConnJack;
5349 }
5350 #endif
5351
5352 // ------------------------------------------------------------------------------------------
5353 // Described at:
5354 // http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
5355
5356 PaError PaWasapi_GetJackDescription(PaDeviceIndex device, int jackIndex, PaWasapiJackDescription *pJackDescription)
5357 {
5358 #ifndef PA_WINRT
5359 PaError ret;
5360 HRESULT hr = S_OK;
5361 PaWasapiDeviceInfo *deviceInfo;
5362 IDeviceTopology *pDeviceTopology = NULL;
5363 IConnector *pConnFrom = NULL;
5364 IConnector *pConnTo = NULL;
5365 IPart *pPart = NULL;
5366 IKsJackDescription *pJackDesc = NULL;
5367 KSJACK_DESCRIPTION jack = { 0 };
5368
5369 if ((ret = _GetWasapiDeviceInfoByDeviceIndex(&deviceInfo, device)) != paNoError)
5370 return ret;
5371
5372 // Get the endpoint device's IDeviceTopology interface
5373 hr = IMMDevice_Activate(deviceInfo->device, &pa_IID_IDeviceTopology,
5374 CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
5375 IF_FAILED_JUMP(hr, error);
5376
5377 // The device topology for an endpoint device always contains just one connector (connector number 0)
5378 hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
5379 IF_FAILED_JUMP(hr, error);
5380
5381 // Step across the connection to the jack on the adapter
5382 hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
5383 if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
5384 {
5385 // The adapter device is not currently active
5386 hr = E_NOINTERFACE;
5387 }
5388 IF_FAILED_JUMP(hr, error);
5389
5390 // Get the connector's IPart interface
5391 hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
5392 IF_FAILED_JUMP(hr, error);
5393
5394 // Activate the connector's IKsJackDescription interface
5395 hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
5396 IF_FAILED_JUMP(hr, error);
5397
5398 // Test to return jack description struct for index 0
5399 hr = IKsJackDescription_GetJackDescription(pJackDesc, jackIndex, &jack);
5400 IF_FAILED_JUMP(hr, error);
5401
5402 // Convert WASAPI values to PA format
5403 pJackDescription->channelMapping = jack.ChannelMapping;
5404 pJackDescription->color = jack.Color;
5405 pJackDescription->connectionType = _ConvertJackConnectionTypeWASAPIToPA(jack.ConnectionType);
5406 pJackDescription->genLocation = _ConvertJackGenLocationWASAPIToPA(jack.GenLocation);
5407 pJackDescription->geoLocation = _ConvertJackGeoLocationWASAPIToPA(jack.GeoLocation);
5408 pJackDescription->isConnected = jack.IsConnected;
5409 pJackDescription->portConnection = _ConvertJackPortConnectionWASAPIToPA(jack.PortConnection);
5410
5411 // Ok
5412 ret = paNoError;
5413
5414 error:
5415
5416 SAFE_RELEASE(pDeviceTopology);
5417 SAFE_RELEASE(pConnFrom);
5418 SAFE_RELEASE(pConnTo);
5419 SAFE_RELEASE(pPart);
5420 SAFE_RELEASE(pJackDesc);
5421
5422 LogHostError(hr);
5423 return ret;
5424
5425 #else
5426 (void)device;
5427 (void)jackIndex;
5428 (void)pJackDescription;
5429 return paUnanticipatedHostError;
5430 #endif
5431 }
5432
5433 // ------------------------------------------------------------------------------------------
5434 PaError PaWasapi_GetAudioClient(PaStream *pStream, void **pAudioClient, int bOutput)
5435 {
5436 PaWasapiStream *stream = (PaWasapiStream *)pStream;
5437 if (stream == NULL)
5438 return paBadStreamPtr;
5439
5440 if (pAudioClient == NULL)
5441 return paUnanticipatedHostError;
5442
5443 (*pAudioClient) = (bOutput == TRUE ? stream->out.clientParent : stream->in.clientParent);
5444
5445 return paNoError;
5446 }
5447
5448 // ------------------------------------------------------------------------------------------
5449 #ifdef PA_WINRT
5450 static void CopyNameOrIdString(WCHAR *dst, const UINT32 dstMaxCount, const WCHAR *src)
5451 {
5452 UINT32 i;
5453
5454 for (i = 0; i < dstMaxCount; ++i)
5455 dst[i] = 0;
5456
5457 if (src != NULL)
5458 {
5459 for (i = 0; (src[i] != 0) && (i < dstMaxCount); ++i)
5460 dst[i] = src[i];
5461 }
5462 }
5463 #endif
5464
5465 // ------------------------------------------------------------------------------------------
5466 PaError PaWasapiWinrt_SetDefaultDeviceId( const unsigned short *pId, int bOutput )
5467 {
5468 #ifdef PA_WINRT
5469 INT32 i;
5470 PaWasapiWinrtDeviceListRole *role = (bOutput ? &g_DeviceListInfo.render : &g_DeviceListInfo.capture);
5471
5472 assert(STATIC_ARRAY_SIZE(role->defaultId) == PA_WASAPI_DEVICE_ID_LEN);
5473
5474 // Validate Id length
5475 if (pId != NULL)
5476 {
5477 for (i = 0; pId[i] != 0; ++i)
5478 {
5479 if (i >= PA_WASAPI_DEVICE_ID_LEN)
5480 return paBufferTooBig;
5481 }
5482 }
5483
5484 // Set Id (or reset to all 0 if NULL is provided)
5485 CopyNameOrIdString(role->defaultId, STATIC_ARRAY_SIZE(role->defaultId), pId);
5486
5487 return paNoError;
5488 #else
5489 return paIncompatibleStreamHostApi;
5490 #endif
5491 }
5492
5493 // ------------------------------------------------------------------------------------------
5494 PaError PaWasapiWinrt_PopulateDeviceList( const unsigned short **pId, const unsigned short **pName,
5495 const PaWasapiDeviceRole *pRole, unsigned int count, int bOutput )
5496 {
5497 #ifdef PA_WINRT
5498 UINT32 i, j;
5499 PaWasapiWinrtDeviceListRole *role = (bOutput ? &g_DeviceListInfo.render : &g_DeviceListInfo.capture);
5500
5501 memset(&role->devices, 0, sizeof(role->devices));
5502 role->deviceCount = 0;
5503
5504 if (count == 0)
5505 return paNoError;
5506 else
5507 if (count > PA_WASAPI_DEVICE_MAX_COUNT)
5508 return paBufferTooBig;
5509
5510 // pName or pRole are optional
5511 if (pId == NULL)
5512 return paInsufficientMemory;
5513
5514 // Validate Id and Name lengths
5515 for (i = 0; i < count; ++i)
5516 {
5517 const unsigned short *id = pId[i];
5518 const unsigned short *name = pName[i];
5519
5520 for (j = 0; id[j] != 0; ++j)
5521 {
5522 if (j >= PA_WASAPI_DEVICE_ID_LEN)
5523 return paBufferTooBig;
5524 }
5525
5526 for (j = 0; name[j] != 0; ++j)
5527 {
5528 if (j >= PA_WASAPI_DEVICE_NAME_LEN)
5529 return paBufferTooBig;
5530 }
5531 }
5532
5533 // Set Id and Name (or reset to all 0 if NULL is provided)
5534 for (i = 0; i < count; ++i)
5535 {
5536 CopyNameOrIdString(role->devices[i].id, STATIC_ARRAY_SIZE(role->devices[i].id), pId[i]);
5537 CopyNameOrIdString(role->devices[i].name, STATIC_ARRAY_SIZE(role->devices[i].name), pName[i]);
5538 role->devices[i].formFactor = (pRole != NULL ? (EndpointFormFactor)pRole[i] : UnknownFormFactor);
5539
5540 // Count device if it has at least the Id
5541 role->deviceCount += (role->devices[i].id[0] != 0);
5542 }
5543
5544 return paNoError;
5545 #else
5546 return paIncompatibleStreamHostApi;
5547 #endif
5548 }
5549
5550 // ------------------------------------------------------------------------------------------
5551 PaError PaWasapi_SetStreamStateHandler( PaStream *pStream, PaWasapiStreamStateCallback fnStateHandler, void *pUserData )
5552 {
5553 PaWasapiStream *stream = (PaWasapiStream *)pStream;
5554 if (stream == NULL)
5555 return paBadStreamPtr;
5556
5557 stream->fnStateHandler = fnStateHandler;
5558 stream->pStateHandlerUserData = pUserData;
5559
5560 return paNoError;
5561 }
5562
5563 // ------------------------------------------------------------------------------------------
5564 HRESULT _PollGetOutputFramesAvailable(PaWasapiStream *stream, UINT32 *available)
5565 {
5566 HRESULT hr;
5567 UINT32 frames = stream->out.framesPerHostCallback,
5568 padding = 0;
5569
5570 (*available) = 0;
5571
5572 // get read position
5573 if ((hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &padding)) != S_OK)
5574 return LogHostError(hr);
5575
5576 // get available
5577 frames -= padding;
5578
5579 // set
5580 (*available) = frames;
5581 return hr;
5582 }
5583
5584 // ------------------------------------------------------------------------------------------
5585 HRESULT _PollGetInputFramesAvailable(PaWasapiStream *stream, UINT32 *available)
5586 {
5587 HRESULT hr;
5588
5589 (*available) = 0;
5590
5591 // GetCurrentPadding() has opposite meaning to Output stream
5592 if ((hr = IAudioClient_GetCurrentPadding(stream->in.clientProc, available)) != S_OK)
5593 return LogHostError(hr);
5594
5595 return hr;
5596 }
5597
5598 // ------------------------------------------------------------------------------------------
5599 static HRESULT ProcessOutputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor, UINT32 frames)
5600 {
5601 HRESULT hr;
5602 BYTE *data = NULL;
5603
5604 // Get buffer
5605 if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, frames, &data)) != S_OK)
5606 {
5607 // Both modes, Shared and Exclusive, can fail with AUDCLNT_E_BUFFER_TOO_LARGE error
5608 #if 0
5609 if (stream->out.shareMode == AUDCLNT_SHAREMODE_SHARED)
5610 {
5611 // Using GetCurrentPadding to overcome AUDCLNT_E_BUFFER_TOO_LARGE in
5612 // shared mode results in no sound in Event-driven mode (MSDN does not
5613 // document this, or is it WASAPI bug?), thus we better
5614 // try to acquire buffer next time when GetBuffer allows to do so.
5615 #if 0
5616 // Get Read position
5617 UINT32 padding = 0;
5618 hr = IAudioClient_GetCurrentPadding(stream->out.clientProc, &padding);
5619 if (hr != S_OK)
5620 return LogHostError(hr);
5621
5622 // Get frames to write
5623 frames -= padding;
5624 if (frames == 0)
5625 return S_OK;
5626
5627 if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, frames, &data)) != S_OK)
5628 return LogHostError(hr);
5629 #else
5630 if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
5631 return S_OK; // be silent in shared mode, try again next time
5632 #endif
5633 }
5634 else
5635 return LogHostError(hr);
5636 #else
5637 if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
5638 return S_OK; // try again next time
5639
5640 return LogHostError(hr);
5641 #endif
5642 }
5643
5644 // Process data
5645 if (stream->out.monoMixer != NULL)
5646 {
5647 // expand buffer
5648 UINT32 mono_frames_size = frames * (stream->out.wavex.Format.wBitsPerSample / 8);
5649 if (mono_frames_size > stream->out.monoBufferSize)
5650 {
5651 stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
5652 if (stream->out.monoBuffer == NULL)
5653 {
5654 hr = E_OUTOFMEMORY;
5655 LogHostError(hr);
5656 return hr;
5657 }
5658 }
5659
5660 // process
5661 processor[S_OUTPUT].processor(NULL, 0, (BYTE *)stream->out.monoBuffer, frames, processor[S_OUTPUT].userData);
5662
5663 // mix 1 to 2 channels
5664 stream->out.monoMixer(data, stream->out.monoBuffer, frames);
5665 }
5666 else
5667 {
5668 processor[S_OUTPUT].processor(NULL, 0, data, frames, processor[S_OUTPUT].userData);
5669 }
5670
5671 // Release buffer
5672 if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, frames, 0)) != S_OK)
5673 LogHostError(hr);
5674
5675 return hr;
5676 }
5677
5678 // ------------------------------------------------------------------------------------------
5679 static HRESULT ProcessInputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor)
5680 {
5681 HRESULT hr = S_OK;
5682 UINT32 frames;
5683 BYTE *data = NULL;
5684 DWORD flags = 0;
5685
5686 for (;;)
5687 {
5688 // Check if blocking call must be interrupted
5689 if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
5690 break;
5691
5692 // Find out if any frames available
5693 frames = 0;
5694 if ((hr = _PollGetInputFramesAvailable(stream, &frames)) != S_OK)
5695 return hr;
5696
5697 // Empty/consumed buffer
5698 if (frames == 0)
5699 break;
5700
5701 // Get the available data in the shared buffer.
5702 if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &data, &frames, &flags, NULL, NULL)) != S_OK)
5703 {
5704 if (hr == AUDCLNT_S_BUFFER_EMPTY)
5705 {
5706 hr = S_OK;
5707 break; // Empty/consumed buffer
5708 }
5709
5710 return LogHostError(hr);
5711 break;
5712 }
5713
5714 // Detect silence
5715 // if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
5716 // data = NULL;
5717
5718 // Process data
5719 if (stream->in.monoMixer != NULL)
5720 {
5721 // expand buffer
5722 UINT32 mono_frames_size = frames * (stream->in.wavex.Format.wBitsPerSample / 8);
5723 if (mono_frames_size > stream->in.monoBufferSize)
5724 {
5725 stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
5726 if (stream->in.monoBuffer == NULL)
5727 {
5728 hr = E_OUTOFMEMORY;
5729 LogHostError(hr);
5730 return hr;
5731 }
5732 }
5733
5734 // mix 1 to 2 channels
5735 stream->in.monoMixer(stream->in.monoBuffer, data, frames);
5736
5737 // process
5738 processor[S_INPUT].processor((BYTE *)stream->in.monoBuffer, frames, NULL, 0, processor[S_INPUT].userData);
5739 }
5740 else
5741 {
5742 processor[S_INPUT].processor(data, frames, NULL, 0, processor[S_INPUT].userData);
5743 }
5744
5745 // Release buffer
5746 if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, frames)) != S_OK)
5747 return LogHostError(hr);
5748
5749 //break;
5750 }
5751
5752 return hr;
5753 }
5754
5755 // ------------------------------------------------------------------------------------------
5756 void _StreamOnStop(PaWasapiStream *stream)
5757 {
5758 // Stop INPUT/OUTPUT clients
5759 if (!stream->bBlocking)
5760 {
5761 if (stream->in.clientProc != NULL)
5762 IAudioClient_Stop(stream->in.clientProc);
5763 if (stream->out.clientProc != NULL)
5764 IAudioClient_Stop(stream->out.clientProc);
5765 }
5766 else
5767 {
5768 if (stream->in.clientParent != NULL)
5769 IAudioClient_Stop(stream->in.clientParent);
5770 if (stream->out.clientParent != NULL)
5771 IAudioClient_Stop(stream->out.clientParent);
5772 }
5773
5774 // Restore thread priority
5775 if (stream->hAvTask != NULL)
5776 {
5777 PaWasapi_ThreadPriorityRevert(stream->hAvTask);
5778 stream->hAvTask = NULL;
5779 }
5780
5781 // Notify
5782 if (stream->streamRepresentation.streamFinishedCallback != NULL)
5783 stream->streamRepresentation.streamFinishedCallback(stream->streamRepresentation.userData);
5784 }
5785
5786 // ------------------------------------------------------------------------------------------
5787 static BOOL PrepareComPointers(PaWasapiStream *stream, BOOL *threadComInitialized)
5788 {
5789 HRESULT hr;
5790
5791 /*
5792 If COM is already initialized CoInitialize will either return
5793 FALSE, or RPC_E_CHANGED_MODE if it was initialized in a different
5794 threading mode. In either case we shouldn't consider it an error
5795 but we need to be careful to not call CoUninitialize() if
5796 RPC_E_CHANGED_MODE was returned.
5797 */
5798 hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
5799 if (FAILED(hr) && (hr != RPC_E_CHANGED_MODE))
5800 {
5801 PRINT(("WASAPI: failed ProcThreadEvent CoInitialize"));
5802 return FALSE;
5803 }
5804 if (hr != RPC_E_CHANGED_MODE)
5805 *threadComInitialized = TRUE;
5806
5807 // Unmarshal stream pointers for safe COM operation
5808 hr = UnmarshalStreamComPointers(stream);
5809 if (hr != S_OK)
5810 {
5811 PRINT(("WASAPI: Error unmarshaling stream COM pointers. HRESULT: %i\n", hr));
5812 CoUninitialize();
5813 return FALSE;
5814 }
5815
5816 return TRUE;
5817 }
5818
5819 // ------------------------------------------------------------------------------------------
5820 static void FinishComPointers(PaWasapiStream *stream, BOOL threadComInitialized)
5821 {
5822 // Release unmarshaled COM pointers
5823 ReleaseUnmarshaledComPointers(stream);
5824
5825 // Cleanup COM for this thread
5826 if (threadComInitialized == TRUE)
5827 CoUninitialize();
5828 }
5829
5830 // ------------------------------------------------------------------------------------------
5831 PA_THREAD_FUNC ProcThreadEvent(void *param)
5832 {
5833 PaWasapiHostProcessor processor[S_COUNT];
5834 HRESULT hr = S_OK;
5835 DWORD dwResult;
5836 PaWasapiStream *stream = (PaWasapiStream *)param;
5837 PaWasapiHostProcessor defaultProcessor;
5838 BOOL setEvent[S_COUNT] = { FALSE, FALSE };
5839 BOOL waitAllEvents = FALSE;
5840 BOOL threadComInitialized = FALSE;
5841 SystemTimer timer;
5842
5843 // Notify: state
5844 NotifyStateChanged(stream, paWasapiStreamStateThreadPrepare, ERROR_SUCCESS);
5845
5846 // Prepare COM pointers
5847 if (!PrepareComPointers(stream, &threadComInitialized))
5848 return (UINT32)paUnanticipatedHostError;
5849
5850 // Request fine (1 ms) granularity of the system timer functions for precise operation of waitable timers
5851 SystemTimer_SetGranularity(&timer, 1);
5852
5853 // Waiting on all events in case of Full-Duplex/Exclusive mode.
5854 if ((stream->in.clientProc != NULL) && (stream->out.clientProc != NULL))
5855 {
5856 waitAllEvents = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) &&
5857 (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE);
5858 }
5859
5860 // Setup data processors
5861 defaultProcessor.processor = WaspiHostProcessingLoop;
5862 defaultProcessor.userData = stream;
5863 processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
5864 processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
5865
5866 // Boost thread priority
5867 PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
5868
5869 // Create events
5870 if (stream->event[S_OUTPUT] == NULL)
5871 {
5872 stream->event[S_OUTPUT] = CreateEvent(NULL, FALSE, FALSE, NULL);
5873 setEvent[S_OUTPUT] = TRUE;
5874 }
5875 if (stream->event[S_INPUT] == NULL)
5876 {
5877 stream->event[S_INPUT] = CreateEvent(NULL, FALSE, FALSE, NULL);
5878 setEvent[S_INPUT] = TRUE;
5879 }
5880 if ((stream->event[S_OUTPUT] == NULL) || (stream->event[S_INPUT] == NULL))
5881 {
5882 PRINT(("WASAPI Thread: failed creating Input/Output event handle\n"));
5883 goto thread_error;
5884 }
5885
5886 // Signal: stream running
5887 stream->running = TRUE;
5888
5889 // Notify: thread started
5890 SetEvent(stream->hThreadStart);
5891
5892 // Initialize event & start INPUT stream
5893 if (stream->in.clientProc)
5894 {
5895 // Create & set handle
5896 if (setEvent[S_INPUT])
5897 {
5898 if ((hr = IAudioClient_SetEventHandle(stream->in.clientProc, stream->event[S_INPUT])) != S_OK)
5899 {
5900 LogHostError(hr);
5901 goto thread_error;
5902 }
5903 }
5904
5905 // Start
5906 if ((hr = IAudioClient_Start(stream->in.clientProc)) != S_OK)
5907 {
5908 LogHostError(hr);
5909 goto thread_error;
5910 }
5911 }
5912
5913 // Initialize event & start OUTPUT stream
5914 if (stream->out.clientProc)
5915 {
5916 // Create & set handle
5917 if (setEvent[S_OUTPUT])
5918 {
5919 if ((hr = IAudioClient_SetEventHandle(stream->out.clientProc, stream->event[S_OUTPUT])) != S_OK)
5920 {
5921 LogHostError(hr);
5922 goto thread_error;
5923 }
5924 }
5925
5926 // Preload buffer before start
5927 if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
5928 {
5929 LogHostError(hr);
5930 goto thread_error;
5931 }
5932
5933 // Start
5934 if ((hr = IAudioClient_Start(stream->out.clientProc)) != S_OK)
5935 {
5936 LogHostError(hr);
5937 goto thread_error;
5938 }
5939
5940 }
5941
5942 // Notify: state
5943 NotifyStateChanged(stream, paWasapiStreamStateThreadStart, ERROR_SUCCESS);
5944
5945 // Processing Loop
5946 for (;;)
5947 {
5948 // 10 sec timeout (on timeout stream will auto-stop when processed by WAIT_TIMEOUT case)
5949 dwResult = WaitForMultipleObjects(S_COUNT, stream->event, waitAllEvents, 10*1000);
5950
5951 // Check for close event (after wait for buffers to avoid any calls to user
5952 // callback when hCloseRequest was set)
5953 if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
5954 break;
5955
5956 // Process S_INPUT/S_OUTPUT
5957 switch (dwResult)
5958 {
5959 case WAIT_TIMEOUT: {
5960 PRINT(("WASAPI Thread: WAIT_TIMEOUT - probably bad audio driver or Vista x64 bug: use paWinWasapiPolling instead\n"));
5961 goto thread_end;
5962 break; }
5963
5964 // Input stream
5965 case WAIT_OBJECT_0 + S_INPUT: {
5966
5967 if (stream->captureClient == NULL)
5968 break;
5969
5970 if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
5971 {
5972 LogHostError(hr);
5973 goto thread_error;
5974 }
5975
5976 break; }
5977
5978 // Output stream
5979 case WAIT_OBJECT_0 + S_OUTPUT: {
5980
5981 if (stream->renderClient == NULL)
5982 break;
5983
5984 if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
5985 {
5986 LogHostError(hr);
5987 goto thread_error;
5988 }
5989
5990 break; }
5991 }
5992 }
5993
5994 thread_end:
5995
5996 // Process stop
5997 _StreamOnStop(stream);
5998
5999 // Release unmarshaled COM pointers
6000 FinishComPointers(stream, threadComInitialized);
6001
6002 // Restore system timer granularity
6003 SystemTimer_RestoreGranularity(&timer);
6004
6005 // Notify: not running
6006 stream->running = FALSE;
6007
6008 // Notify: thread exited
6009 SetEvent(stream->hThreadExit);
6010
6011 // Notify: state
6012 NotifyStateChanged(stream, paWasapiStreamStateThreadStop, hr);
6013
6014 return 0;
6015
6016 thread_error:
6017
6018 // Prevent deadlocking in Pa_StreamStart
6019 SetEvent(stream->hThreadStart);
6020
6021 // Exit
6022 goto thread_end;
6023 }
6024
6025 // ------------------------------------------------------------------------------------------
6026 static UINT32 GetSleepTime(PaWasapiStream *stream, UINT32 sleepTimeIn, UINT32 sleepTimeOut, UINT32 userFramesOut)
6027 {
6028 UINT32 sleepTime;
6029
6030 // According to the issue [https://github.com/PortAudio/portaudio/issues/303] glitches may occur when user frames
6031 // equal to 1/2 of the host buffer frames, therefore the empirical workaround for this problem is to lower
6032 // the sleep time by 2
6033 if (userFramesOut != 0)
6034 {
6035 UINT32 chunks = stream->out.framesPerHostCallback / userFramesOut;
6036 if (chunks <= 2)
6037 {
6038 sleepTimeOut /= 2;
6039 PRINT(("WASAPI: underrun workaround, sleep [%d] ms - 1/2 of the user buffer[%d] | host buffer[%d]\n", sleepTimeOut, userFramesOut, stream->out.framesPerHostCallback));
6040 }
6041 }
6042
6043 // Choose the smallest
6044 if ((sleepTimeIn != 0) && (sleepTimeOut != 0))
6045 sleepTime = min(sleepTimeIn, sleepTimeOut);
6046 else
6047 sleepTime = (sleepTimeIn ? sleepTimeIn : sleepTimeOut);
6048
6049 return sleepTime;
6050 }
6051
6052 // ------------------------------------------------------------------------------------------
6053 static UINT32 ConfigureLoopSleepTimeAndScheduler(PaWasapiStream *stream, ThreadIdleScheduler *scheduler)
6054 {
6055 UINT32 sleepTime, sleepTimeIn, sleepTimeOut;
6056 UINT32 userFramesIn = stream->in.framesPerHostCallback / WASAPI_PACKETS_PER_INPUT_BUFFER;
6057 UINT32 userFramesOut = stream->out.framesPerBuffer;
6058
6059 // Adjust polling time for non-paUtilFixedHostBufferSize, input stream is not adjustable as it is being
6060 // polled according to its packet length
6061 if (stream->bufferMode != paUtilFixedHostBufferSize)
6062 {
6063 userFramesOut = (stream->bufferProcessor.framesPerUserBuffer ? stream->bufferProcessor.framesPerUserBuffer :
6064 stream->out.params.frames_per_buffer);
6065 }
6066
6067 // Calculate timeout for the next polling attempt
6068 sleepTimeIn = GetFramesSleepTime(userFramesIn, stream->in.wavex.Format.nSamplesPerSec);
6069 sleepTimeOut = GetFramesSleepTime(userFramesOut, stream->out.wavex.Format.nSamplesPerSec);
6070
6071 // WASAPI input packets tend to expire very easily, let's limit sleep time to 2 milliseconds
6072 // for all cases. Please propose better solution if any
6073 if (sleepTimeIn > 2)
6074 sleepTimeIn = 2;
6075
6076 sleepTime = GetSleepTime(stream, sleepTimeIn, sleepTimeOut, userFramesOut);
6077
6078 // Make sure not 0, othervise use ThreadIdleScheduler to bounce between [0, 1] ms to avoid too busy loop
6079 if (sleepTime == 0)
6080 {
6081 sleepTimeIn = GetFramesSleepTimeMicroseconds(userFramesIn, stream->in.wavex.Format.nSamplesPerSec);
6082 sleepTimeOut = GetFramesSleepTimeMicroseconds(userFramesOut, stream->out.wavex.Format.nSamplesPerSec);
6083
6084 sleepTime = GetSleepTime(stream, sleepTimeIn, sleepTimeOut, userFramesOut);
6085
6086 // Setup thread sleep scheduler
6087 ThreadIdleScheduler_Setup(scheduler, 1, sleepTime/* microseconds here */);
6088 sleepTime = 0;
6089 }
6090
6091 return sleepTime;
6092 }
6093
6094 // ------------------------------------------------------------------------------------------
6095 static inline INT32 GetNextSleepTime(SystemTimer *timer, ThreadIdleScheduler *scheduler, LONGLONG startTime,
6096 UINT32 sleepTime)
6097 {
6098 INT32 nextSleepTime;
6099 INT32 procTime;
6100
6101 // Get next sleep time
6102 if (sleepTime == 0)
6103 nextSleepTime = ThreadIdleScheduler_NextSleep(scheduler);
6104 else
6105 nextSleepTime = sleepTime;
6106
6107 // Adjust next sleep time dynamically depending on how much time was spent in ProcessOutputBuffer/ProcessInputBuffer
6108 // therefore periodicity will not jitter or be increased for the amount of time spent in processing;
6109 // example when sleepTime is 10 ms where [] is polling time slot, {} processing time slot:
6110 //
6111 // [9],{2},[8],{1},[9],{1},[9],{3},[7],{2},[8],{3},[7],{2},[8],{2},[8],{3},[7],{2},[8],...
6112 //
6113 procTime = (INT32)(SystemTimer_GetTime(timer) - startTime);
6114 nextSleepTime -= procTime;
6115 if (nextSleepTime < timer->granularity)
6116 nextSleepTime = 0;
6117 else
6118 if (timer->granularity > 1)
6119 nextSleepTime = ALIGN_BWD(nextSleepTime, timer->granularity);
6120
6121 #ifdef PA_WASAPI_LOG_TIME_SLOTS
6122 printf("{%d},", procTime);
6123 #endif
6124
6125 return nextSleepTime;
6126 }
6127
6128 // ------------------------------------------------------------------------------------------
6129 PA_THREAD_FUNC ProcThreadPoll(void *param)
6130 {
6131 PaWasapiHostProcessor processor[S_COUNT];
6132 HRESULT hr = S_OK;
6133 PaWasapiStream *stream = (PaWasapiStream *)param;
6134 PaWasapiHostProcessor defaultProcessor;
6135 INT32 i;
6136 ThreadIdleScheduler scheduler;
6137 SystemTimer timer;
6138 LONGLONG startTime;
6139 UINT32 sleepTime;
6140 INT32 nextSleepTime = 0; //! Do first loop without waiting as time could be spent when calling other APIs before ProcessXXXBuffer.
6141 BOOL threadComInitialized = FALSE;
6142 #ifdef PA_WASAPI_LOG_TIME_SLOTS
6143 LONGLONG startWaitTime;
6144 #endif
6145
6146 // Notify: state
6147 NotifyStateChanged(stream, paWasapiStreamStateThreadPrepare, ERROR_SUCCESS);
6148
6149 // Prepare COM pointers
6150 if (!PrepareComPointers(stream, &threadComInitialized))
6151 return (UINT32)paUnanticipatedHostError;
6152
6153 // Request fine (1 ms) granularity of the system timer functions to guarantee correct logic around WaitForSingleObject
6154 SystemTimer_SetGranularity(&timer, 1);
6155
6156 // Calculate sleep time of the processing loop (inside WaitForSingleObject)
6157 sleepTime = ConfigureLoopSleepTimeAndScheduler(stream, &scheduler);
6158
6159 // Setup data processors
6160 defaultProcessor.processor = WaspiHostProcessingLoop;
6161 defaultProcessor.userData = stream;
6162 processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
6163 processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
6164
6165 // Boost thread priority
6166 PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
6167
6168 // Signal: stream running
6169 stream->running = TRUE;
6170
6171 // Notify: thread started
6172 SetEvent(stream->hThreadStart);
6173
6174 // Initialize event & start INPUT stream
6175 if (stream->in.clientProc)
6176 {
6177 if ((hr = IAudioClient_Start(stream->in.clientProc)) != S_OK)
6178 {
6179 LogHostError(hr);
6180 goto thread_error;
6181 }
6182 }
6183
6184 // Initialize event & start OUTPUT stream
6185 if (stream->out.clientProc)
6186 {
6187 // Preload buffer (obligatory, othervise ->Start() will fail), avoid processing
6188 // when in full-duplex mode as it requires input processing as well
6189 if (!PA_WASAPI__IS_FULLDUPLEX(stream))
6190 {
6191 UINT32 frames = 0;
6192 if ((hr = _PollGetOutputFramesAvailable(stream, &frames)) == S_OK)
6193 {
6194 if (stream->bufferMode == paUtilFixedHostBufferSize)
6195 {
6196 // It is important to preload whole host buffer to avoid underruns/glitches when stream is started,
6197 // for more details see the discussion: https://github.com/PortAudio/portaudio/issues/303
6198 while (frames >= stream->out.framesPerBuffer)
6199 {
6200 if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
6201 {
6202 LogHostError(hr); // not fatal, just log
6203 break;
6204 }
6205
6206 frames -= stream->out.framesPerBuffer;
6207 }
6208 }
6209 else
6210 {
6211 // Some devices may not start (will get stuck with 0 ready frames) if data not prefetched
6212 if (frames == 0)
6213 frames = stream->out.framesPerBuffer;
6214
6215 // USB DACs report large buffer in Exclusive mode and if it is filled fully will stuck in
6216 // non playing state, e.g. IAudioClient_GetCurrentPadding() will start reporting max buffer size
6217 // constantly, thus preload data size equal to the user buffer to allow process going
6218 if ((stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) && (frames >= (stream->out.framesPerBuffer * 2)))
6219 frames -= stream->out.framesPerBuffer;
6220
6221 if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
6222 {
6223 LogHostError(hr); // not fatal, just log
6224 }
6225 }
6226 }
6227 else
6228 {
6229 LogHostError(hr); // not fatal, just log
6230 }
6231 }
6232
6233 // Start
6234 if ((hr = IAudioClient_Start(stream->out.clientProc)) != S_OK)
6235 {
6236 LogHostError(hr);
6237 goto thread_error;
6238 }
6239 }
6240
6241 // Notify: state
6242 NotifyStateChanged(stream, paWasapiStreamStateThreadStart, ERROR_SUCCESS);
6243
6244 #ifdef PA_WASAPI_LOG_TIME_SLOTS
6245 startWaitTime = SystemTimer_GetTime(&timer);
6246 #endif
6247
6248 if (!PA_WASAPI__IS_FULLDUPLEX(stream))
6249 {
6250 // Processing Loop
6251 while (WaitForSingleObject(stream->hCloseRequest, nextSleepTime) == WAIT_TIMEOUT)
6252 {
6253 startTime = SystemTimer_GetTime(&timer);
6254
6255 #ifdef PA_WASAPI_LOG_TIME_SLOTS
6256 printf("[%d|%d],", nextSleepTime, (INT32)(startTime - startWaitTime));
6257 #endif
6258
6259 for (i = 0; i < S_COUNT; ++i)
6260 {
6261 // Process S_INPUT/S_OUTPUT
6262 switch (i)
6263 {
6264 // Input stream
6265 case S_INPUT: {
6266
6267 if (stream->captureClient == NULL)
6268 break;
6269
6270 if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
6271 {
6272 LogHostError(hr);
6273 goto thread_error;
6274 }
6275
6276 break; }
6277
6278 // Output stream
6279 case S_OUTPUT: {
6280
6281 UINT32 framesAvail;
6282
6283 if (stream->renderClient == NULL)
6284 break;
6285
6286 // Get available frames
6287 if ((hr = _PollGetOutputFramesAvailable(stream, &framesAvail)) != S_OK)
6288 {
6289 LogHostError(hr);
6290 goto thread_error;
6291 }
6292
6293 // Output data to the user callback
6294 if (stream->bufferMode == paUtilFixedHostBufferSize)
6295 {
6296 UINT32 framesProc = stream->out.framesPerBuffer;
6297
6298 // If we got less frames avoid sleeping again as it might be the corner case and buffer
6299 // has sufficient number of frames now, in case 'out.framesPerBuffer' is 1/2 of the host
6300 // buffer sleeping again may cause underruns. Do short busy waiting (normally might take
6301 // 1-2 iterations)
6302 if (framesAvail < framesProc)
6303 {
6304 nextSleepTime = 0;
6305 continue;
6306 }
6307
6308 while (framesAvail >= framesProc)
6309 {
6310 if ((hr = ProcessOutputBuffer(stream, processor, framesProc)) != S_OK)
6311 {
6312 LogHostError(hr);
6313 goto thread_error;
6314 }
6315
6316 framesAvail -= framesProc;
6317 }
6318 }
6319 else
6320 if (framesAvail != 0)
6321 {
6322 if ((hr = ProcessOutputBuffer(stream, processor, framesAvail)) != S_OK)
6323 {
6324 LogHostError(hr);
6325 goto thread_error;
6326 }
6327 }
6328
6329 break; }
6330 }
6331 }
6332
6333 // Get next sleep time
6334 nextSleepTime = GetNextSleepTime(&timer, &scheduler, startTime, sleepTime);
6335
6336 #ifdef PA_WASAPI_LOG_TIME_SLOTS
6337 startWaitTime = SystemTimer_GetTime(&timer);
6338 #endif
6339 }
6340 }
6341 else
6342 {
6343 // Processing Loop (full-duplex)
6344 while (WaitForSingleObject(stream->hCloseRequest, nextSleepTime) == WAIT_TIMEOUT)
6345 {
6346 UINT32 i_frames = 0, i_processed = 0, o_frames = 0;
6347 BYTE *i_data = NULL, *o_data = NULL, *o_data_host = NULL;
6348 DWORD i_flags = 0;
6349
6350 startTime = SystemTimer_GetTime(&timer);
6351
6352 #ifdef PA_WASAPI_LOG_TIME_SLOTS
6353 printf("[%d|%d],", nextSleepTime, (INT32)(startTime - startWaitTime));
6354 #endif
6355
6356 // get available frames
6357 if ((hr = _PollGetOutputFramesAvailable(stream, &o_frames)) != S_OK)
6358 {
6359 LogHostError(hr);
6360 break;
6361 }
6362
6363 while (o_frames != 0)
6364 {
6365 // get host input buffer
6366 if ((hr = IAudioCaptureClient_GetBuffer(stream->captureClient, &i_data, &i_frames, &i_flags, NULL, NULL)) != S_OK)
6367 {
6368 if (hr == AUDCLNT_S_BUFFER_EMPTY)
6369 break; // no data in capture buffer
6370
6371 LogHostError(hr);
6372 break;
6373 }
6374
6375 // process equal amount of frames
6376 if (o_frames >= i_frames)
6377 {
6378 // process input amount of frames
6379 UINT32 o_processed = i_frames;
6380
6381 // get host output buffer
6382 if ((hr = IAudioRenderClient_GetBuffer(stream->renderClient, o_processed, &o_data)) == S_OK)
6383 {
6384 // processed amount of i_frames
6385 i_processed = i_frames;
6386 o_data_host = o_data;
6387
6388 // convert output mono
6389 if (stream->out.monoMixer)
6390 {
6391 UINT32 mono_frames_size = o_processed * (stream->out.wavex.Format.wBitsPerSample / 8);
6392 // expand buffer
6393 if (mono_frames_size > stream->out.monoBufferSize)
6394 {
6395 stream->out.monoBuffer = PaWasapi_ReallocateMemory(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
6396 if (stream->out.monoBuffer == NULL)
6397 {
6398 // release input buffer
6399 IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
6400 // release output buffer
6401 IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
6402
6403 LogPaError(paInsufficientMemory);
6404 goto thread_error;
6405 }
6406 }
6407
6408 // replace buffer pointer
6409 o_data = (BYTE *)stream->out.monoBuffer;
6410 }
6411
6412 // convert input mono
6413 if (stream->in.monoMixer)
6414 {
6415 UINT32 mono_frames_size = i_processed * (stream->in.wavex.Format.wBitsPerSample / 8);
6416 // expand buffer
6417 if (mono_frames_size > stream->in.monoBufferSize)
6418 {
6419 stream->in.monoBuffer = PaWasapi_ReallocateMemory(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
6420 if (stream->in.monoBuffer == NULL)
6421 {
6422 // release input buffer
6423 IAudioCaptureClient_ReleaseBuffer(stream->captureClient, 0);
6424 // release output buffer
6425 IAudioRenderClient_ReleaseBuffer(stream->renderClient, 0, 0);
6426
6427 LogPaError(paInsufficientMemory);
6428 goto thread_error;
6429 }
6430 }
6431
6432 // mix 2 to 1 input channels
6433 stream->in.monoMixer(stream->in.monoBuffer, i_data, i_processed);
6434
6435 // replace buffer pointer
6436 i_data = (BYTE *)stream->in.monoBuffer;
6437 }
6438
6439 // process
6440 processor[S_FULLDUPLEX].processor(i_data, i_processed, o_data, o_processed, processor[S_FULLDUPLEX].userData);
6441
6442 // mix 1 to 2 output channels
6443 if (stream->out.monoBuffer)
6444 stream->out.monoMixer(o_data_host, stream->out.monoBuffer, o_processed);
6445
6446 // release host output buffer
6447 if ((hr = IAudioRenderClient_ReleaseBuffer(stream->renderClient, o_processed, 0)) != S_OK)
6448 LogHostError(hr);
6449
6450 o_frames -= o_processed;
6451 }
6452 else
6453 {
6454 if (stream->out.shareMode != AUDCLNT_SHAREMODE_SHARED)
6455 LogHostError(hr); // be silent in shared mode, try again next time
6456 }
6457 }
6458 else
6459 {
6460 i_processed = 0;
6461 goto fd_release_buffer_in;
6462 }
6463
6464 fd_release_buffer_in:
6465
6466 // release host input buffer
6467 if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->captureClient, i_processed)) != S_OK)
6468 {
6469 LogHostError(hr);
6470 break;
6471 }
6472
6473 // break processing, input hasn't been accumulated yet
6474 if (i_processed == 0)
6475 break;
6476 }
6477
6478 // Get next sleep time
6479 nextSleepTime = GetNextSleepTime(&timer, &scheduler, startTime, sleepTime);
6480
6481 #ifdef PA_WASAPI_LOG_TIME_SLOTS
6482 startWaitTime = SystemTimer_GetTime(&timer);
6483 #endif
6484 }
6485 }
6486
6487 thread_end:
6488
6489 // Process stop
6490 _StreamOnStop(stream);
6491
6492 // Release unmarshaled COM pointers
6493 FinishComPointers(stream, threadComInitialized);
6494
6495 // Restore system timer granularity
6496 SystemTimer_RestoreGranularity(&timer);
6497
6498 // Notify: not running
6499 stream->running = FALSE;
6500
6501 // Notify: thread exited
6502 SetEvent(stream->hThreadExit);
6503
6504 // Notify: state
6505 NotifyStateChanged(stream, paWasapiStreamStateThreadStop, hr);
6506
6507 return 0;
6508
6509 thread_error:
6510
6511 // Prevent deadlocking in Pa_StreamStart
6512 SetEvent(stream->hThreadStart);
6513
6514 // Exit
6515 goto thread_end;
6516 }
6517
6518 // ------------------------------------------------------------------------------------------
6519 void *PaWasapi_ReallocateMemory(void *prev, size_t size)
6520 {
6521 void *ret = realloc(prev, size);
6522 if (ret == NULL)
6523 {
6524 PaWasapi_FreeMemory(prev);
6525 return NULL;
6526 }
6527 return ret;
6528 }
6529
6530 // ------------------------------------------------------------------------------------------
6531 void PaWasapi_FreeMemory(void *ptr)
6532 {
6533 free(ptr);
6534 }