Debian Codegraph @

external/portaudio/pa_win_wasapi.c

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