Debian Codegraph @

external/portaudio/pa_win_ds.c

raw
1 #ifdef _WIN32
2 /*
3 * $Id$
4 * Portable Audio I/O Library DirectSound implementation
5 *
6 * Authors: Phil Burk, Robert Marsanyi & Ross Bencina
7 * Based on the Open Source API proposed by Ross Bencina
8 * Copyright (c) 1999-2007 Ross Bencina, Phil Burk, Robert Marsanyi
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 */
44
45 /* Until May 2011 PA/DS has used a multimedia timer to perform the callback.
46 We're replacing this with a new implementation using a thread and a different timer mechanism.
47 Defining PA_WIN_DS_USE_WMME_TIMER uses the old (pre-May 2011) behavior.
48 */
49 //#define PA_WIN_DS_USE_WMME_TIMER
50
51 #include <assert.h>
52 #include <stdio.h>
53 #include <string.h> /* strlen() */
54
55 #define _WIN32_WINNT 0x0400 /* required to get waitable timer APIs */
56 #include <initguid.h> /* make sure ds guids get defined */
57 #include <windows.h>
58 #include <objbase.h>
59
60
61 /*
62 Use the earliest version of DX required, no need to pollute the namespace
63 */
64 #ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
65 #define DIRECTSOUND_VERSION 0x0800
66 #else
67 #define DIRECTSOUND_VERSION 0x0300
68 #endif
69 #include <dsound.h>
70 #ifdef PAWIN_USE_WDMKS_DEVICE_INFO
71 #include <dsconf.h>
72 #endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
73 #ifndef PA_WIN_DS_USE_WMME_TIMER
74 #ifndef UNDER_CE
75 #include <process.h>
76 #endif
77 #endif
78
79 #include "pa_util.h"
80 #include "pa_allocation.h"
81 #include "pa_hostapi.h"
82 #include "pa_stream.h"
83 #include "pa_cpuload.h"
84 #include "pa_process.h"
85 #include "pa_debugprint.h"
86
87 #include "pa_win_ds.h"
88 #include "pa_win_ds_dynlink.h"
89 #include "pa_win_waveformat.h"
90 #include "pa_win_wdmks_utils.h"
91 #include "pa_win_coinitialize.h"
92
93 #if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
94 #pragma comment( lib, "dsound.lib" )
95 #pragma comment( lib, "winmm.lib" )
96 #pragma comment( lib, "kernel32.lib" )
97 #endif
98
99 /* use CreateThread for CYGWIN, _beginthreadex for all others */
100 #ifndef PA_WIN_DS_USE_WMME_TIMER
101
102 #if !defined(__CYGWIN__) && !defined(UNDER_CE)
103 #define CREATE_THREAD (HANDLE)_beginthreadex
104 #undef CLOSE_THREAD_HANDLE /* as per documentation we don't call CloseHandle on a thread created with _beginthreadex */
105 #define PA_THREAD_FUNC static unsigned WINAPI
106 #define PA_THREAD_ID unsigned
107 #else
108 #define CREATE_THREAD CreateThread
109 #define CLOSE_THREAD_HANDLE CloseHandle
110 #define PA_THREAD_FUNC static DWORD WINAPI
111 #define PA_THREAD_ID DWORD
112 #endif
113
114 #if (defined(UNDER_CE))
115 #pragma comment(lib, "Coredll.lib")
116 #elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
117 #pragma comment(lib, "winmm.lib")
118 #endif
119
120 PA_THREAD_FUNC ProcessingThreadProc( void *pArg );
121
122 #if !defined(UNDER_CE)
123 #define PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT /* use waitable timer where possible, otherwise we use a WaitForSingleObject timeout */
124 #endif
125
126 #endif /* !PA_WIN_DS_USE_WMME_TIMER */
127
128
129 /*
130 provided in newer platform sdks and x64
131 */
132 #ifndef DWORD_PTR
133 #if defined(_WIN64)
134 #define DWORD_PTR unsigned __int64
135 #else
136 #define DWORD_PTR unsigned long
137 #endif
138 #endif
139
140 #define PRINT(x) PA_DEBUG(x);
141 #define ERR_RPT(x) PRINT(x)
142 #define DBUG(x) PRINT(x)
143 #define DBUGX(x) PRINT(x)
144
145 #define PA_USE_HIGH_LATENCY (0)
146 #if PA_USE_HIGH_LATENCY
147 #define PA_DS_WIN_9X_DEFAULT_LATENCY_ (.500)
148 #define PA_DS_WIN_NT_DEFAULT_LATENCY_ (.600)
149 #else
150 #define PA_DS_WIN_9X_DEFAULT_LATENCY_ (.140)
151 #define PA_DS_WIN_NT_DEFAULT_LATENCY_ (.280)
152 #endif
153
154 #define PA_DS_WIN_WDM_DEFAULT_LATENCY_ (.120)
155
156 /* we allow the polling period to range between 1 and 100ms.
157 prior to August 2011 we limited the minimum polling period to 10ms.
158 */
159 #define PA_DS_MINIMUM_POLLING_PERIOD_SECONDS (0.001) /* 1ms */
160 #define PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS (0.100) /* 100ms */
161 #define PA_DS_POLLING_JITTER_SECONDS (0.001) /* 1ms */
162
163 #define SECONDS_PER_MSEC (0.001)
164 #define MSECS_PER_SECOND (1000)
165
166 /* prototypes for functions declared in this file */
167
168 #ifdef __cplusplus
169 extern "C"
170 {
171 #endif /* __cplusplus */
172
173 PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
174
175 #ifdef __cplusplus
176 }
177 #endif /* __cplusplus */
178
179 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
180 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
181 PaStream** s,
182 const PaStreamParameters *inputParameters,
183 const PaStreamParameters *outputParameters,
184 double sampleRate,
185 unsigned long framesPerBuffer,
186 PaStreamFlags streamFlags,
187 PaStreamCallback *streamCallback,
188 void *userData );
189 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
190 const PaStreamParameters *inputParameters,
191 const PaStreamParameters *outputParameters,
192 double sampleRate );
193 static PaError CloseStream( PaStream* stream );
194 static PaError StartStream( PaStream *stream );
195 static PaError StopStream( PaStream *stream );
196 static PaError AbortStream( PaStream *stream );
197 static PaError IsStreamStopped( PaStream *s );
198 static PaError IsStreamActive( PaStream *stream );
199 static PaTime GetStreamTime( PaStream *stream );
200 static double GetStreamCpuLoad( PaStream* stream );
201 static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
202 static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
203 static signed long GetStreamReadAvailable( PaStream* stream );
204 static signed long GetStreamWriteAvailable( PaStream* stream );
205
206
207 /* FIXME: should convert hr to a string */
208 #define PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ) \
209 PaUtil_SetLastHostErrorInfo( paDirectSound, hr, "DirectSound error" )
210
211 /************************************************* DX Prototypes **********/
212 static BOOL CALLBACK CollectGUIDsProcW(LPGUID lpGUID,
213 LPCWSTR lpszDesc,
214 LPCWSTR lpszDrvName,
215 LPVOID lpContext );
216
217 /************************************************************************************/
218 /********************** Structures **************************************************/
219 /************************************************************************************/
220 /* PaWinDsHostApiRepresentation - host api datastructure specific to this implementation */
221
222 typedef struct PaWinDsDeviceInfo
223 {
224 PaDeviceInfo inheritedDeviceInfo;
225 GUID guid;
226 GUID *lpGUID;
227 double sampleRates[3];
228 char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
229 char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
230 } PaWinDsDeviceInfo;
231
232 typedef struct
233 {
234 PaUtilHostApiRepresentation inheritedHostApiRep;
235 PaUtilStreamInterface callbackStreamInterface;
236 PaUtilStreamInterface blockingStreamInterface;
237
238 PaUtilAllocationGroup *allocations;
239
240 /* implementation specific data goes here */
241
242 PaWinUtilComInitializationResult comInitializationResult;
243
244 } PaWinDsHostApiRepresentation;
245
246
247 /* PaWinDsStream - a stream data structure specifically for this implementation */
248
249 typedef struct PaWinDsStream
250 {
251 PaUtilStreamRepresentation streamRepresentation;
252 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
253 PaUtilBufferProcessor bufferProcessor;
254
255 /* DirectSound specific data. */
256 #ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
257 LPDIRECTSOUNDFULLDUPLEX8 pDirectSoundFullDuplex8;
258 #endif
259
260 /* Output */
261 LPDIRECTSOUND pDirectSound;
262 LPDIRECTSOUNDBUFFER pDirectSoundPrimaryBuffer;
263 LPDIRECTSOUNDBUFFER pDirectSoundOutputBuffer;
264 DWORD outputBufferWriteOffsetBytes; /* last write position */
265 INT outputBufferSizeBytes;
266 INT outputFrameSizeBytes;
267 /* Try to detect play buffer underflows. */
268 LARGE_INTEGER perfCounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */
269 LARGE_INTEGER previousPlayTime;
270 DWORD previousPlayCursor;
271 UINT outputUnderflowCount;
272 BOOL outputIsRunning;
273 INT finalZeroBytesWritten; /* used to determine when we've flushed the whole buffer */
274
275 /* Input */
276 LPDIRECTSOUNDCAPTURE pDirectSoundCapture;
277 LPDIRECTSOUNDCAPTUREBUFFER pDirectSoundInputBuffer;
278 INT inputFrameSizeBytes;
279 UINT readOffset; /* last read position */
280 UINT inputBufferSizeBytes;
281
282
283 int hostBufferSizeFrames; /* input and output host ringbuffers have the same number of frames */
284 double framesWritten;
285 double secondsPerHostByte; /* Used to optimize latency calculation for outTime */
286 double pollingPeriodSeconds;
287
288 PaStreamCallbackFlags callbackFlags;
289
290 PaStreamFlags streamFlags;
291 int callbackResult;
292 HANDLE processingCompleted;
293
294 /* FIXME - move all below to PaUtilStreamRepresentation */
295 volatile int isStarted;
296 volatile int isActive;
297 volatile int stopProcessing; /* stop thread once existing buffers have been returned */
298 volatile int abortProcessing; /* stop thread immediately */
299
300 UINT systemTimerResolutionPeriodMs; /* set to 0 if we were unable to set the timer period */
301
302 #ifdef PA_WIN_DS_USE_WMME_TIMER
303 MMRESULT timerID;
304 #else
305
306 #ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
307 HANDLE waitableTimer;
308 #endif
309 HANDLE processingThread;
310 PA_THREAD_ID processingThreadId;
311 HANDLE processingThreadCompleted;
312 #endif
313
314 } PaWinDsStream;
315
316
317 /* Set minimal latency based on the current OS version.
318 * NT has higher latency.
319 */
320 static double PaWinDS_GetMinSystemLatencySeconds( void )
321 {
322 /*
323 NOTE: GetVersionEx() is deprecated as of Windows 8.1 and can not be used to reliably detect
324 versions of Windows higher than Windows 8 (due to manifest requirements for reporting higher versions).
325 Microsoft recommends switching to VerifyVersionInfo (available on Win 2k and later), however GetVersionEx
326 is faster, for now we just disable the deprecation warning.
327 See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
328 See: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
329 */
330 #pragma warning (disable : 4996) /* use of GetVersionEx */
331
332 double minLatencySeconds;
333 /* Set minimal latency based on whether NT or other OS.
334 * NT has higher latency.
335 */
336
337 OSVERSIONINFO osvi;
338 osvi.dwOSVersionInfoSize = sizeof( osvi );
339 GetVersionEx( &osvi );
340 DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId ));
341 DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion ));
342 DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion ));
343 /* Check for NT */
344 if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
345 {
346 minLatencySeconds = PA_DS_WIN_NT_DEFAULT_LATENCY_;
347 }
348 else if(osvi.dwMajorVersion >= 5)
349 {
350 minLatencySeconds = PA_DS_WIN_WDM_DEFAULT_LATENCY_;
351 }
352 else
353 {
354 minLatencySeconds = PA_DS_WIN_9X_DEFAULT_LATENCY_;
355 }
356 return minLatencySeconds;
357
358 #pragma warning (default : 4996)
359 }
360
361
362 /*************************************************************************
363 ** Return minimum workable latency required for this host. This is returned
364 ** As the default stream latency in PaDeviceInfo.
365 ** Latency can be optionally set by user by setting an environment variable.
366 ** For example, to set latency to 200 msec, put:
367 **
368 ** set PA_MIN_LATENCY_MSEC=200
369 **
370 ** in the AUTOEXEC.BAT file and reboot.
371 ** If the environment variable is not set, then the latency will be determined
372 ** based on the OS. Windows NT has higher latency than Win95.
373 */
374 #define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC")
375 #define PA_ENV_BUF_SIZE (32)
376
377 static double PaWinDs_GetMinLatencySeconds( double sampleRate )
378 {
379 char envbuf[PA_ENV_BUF_SIZE];
380 DWORD hresult;
381 double minLatencySeconds = 0;
382
383 /* Let user determine minimal latency by setting environment variable. */
384 hresult = GetEnvironmentVariableA( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE );
385 if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) )
386 {
387 minLatencySeconds = atoi( envbuf ) * SECONDS_PER_MSEC;
388 }
389 else
390 {
391 minLatencySeconds = PaWinDS_GetMinSystemLatencySeconds();
392 #if PA_USE_HIGH_LATENCY
393 PRINT(("PA - Minimum Latency set to %f msec!\n", minLatencySeconds * MSECS_PER_SECOND ));
394 #endif
395 }
396
397 return minLatencySeconds;
398 }
399
400
401 /************************************************************************************
402 ** Duplicate and convert the input string using the group allocations allocator.
403 ** A NULL string is converted to a zero length string.
404 ** If memory cannot be allocated, NULL is returned.
405 **/
406 static char *DuplicateDeviceNameString( PaUtilAllocationGroup *allocations, const wchar_t* src )
407 {
408 char *result = 0;
409
410 if( src != NULL )
411 {
412 size_t len = WideCharToMultiByte(CP_UTF8, 0, src, -1, NULL, 0, NULL, NULL);
413
414 result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) );
415 if( result ) {
416 if (WideCharToMultiByte(CP_UTF8, 0, src, -1, result, (int)len, NULL, NULL) == 0) {
417 result = 0;
418 }
419 }
420 }
421 else
422 {
423 result = (char*)PaUtil_GroupAllocateMemory( allocations, 1 );
424 if( result )
425 result[0] = '\0';
426 }
427
428 return result;
429 }
430
431 /************************************************************************************
432 ** DSDeviceNameAndGUID, DSDeviceNameAndGUIDVector used for collecting preliminary
433 ** information during device enumeration.
434 */
435 typedef struct DSDeviceNameAndGUID{
436 char *name; // allocated from parent's allocations, never deleted by this structure
437 GUID guid;
438 LPGUID lpGUID;
439 void *pnpInterface; // wchar_t* interface path, allocated using the DS host api's allocation group
440 } DSDeviceNameAndGUID;
441
442 typedef struct DSDeviceNameAndGUIDVector{
443 PaUtilAllocationGroup *allocations;
444 PaError enumerationError;
445
446 int count;
447 int free;
448 DSDeviceNameAndGUID *items; // Allocated using LocalAlloc()
449 } DSDeviceNameAndGUIDVector;
450
451 typedef struct DSDeviceNamesAndGUIDs{
452 PaWinDsHostApiRepresentation *winDsHostApi;
453 DSDeviceNameAndGUIDVector inputNamesAndGUIDs;
454 DSDeviceNameAndGUIDVector outputNamesAndGUIDs;
455 } DSDeviceNamesAndGUIDs;
456
457 static PaError InitializeDSDeviceNameAndGUIDVector(
458 DSDeviceNameAndGUIDVector *guidVector, PaUtilAllocationGroup *allocations )
459 {
460 PaError result = paNoError;
461
462 guidVector->allocations = allocations;
463 guidVector->enumerationError = paNoError;
464
465 guidVector->count = 0;
466 guidVector->free = 8;
467 guidVector->items = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * guidVector->free );
468 if( guidVector->items == NULL )
469 result = paInsufficientMemory;
470
471 return result;
472 }
473
474 static PaError ExpandDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
475 {
476 PaError result = paNoError;
477 DSDeviceNameAndGUID *newItems;
478 int i;
479
480 /* double size of vector */
481 int size = guidVector->count + guidVector->free;
482 guidVector->free += size;
483
484 newItems = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * size * 2 );
485 if( newItems == NULL )
486 {
487 result = paInsufficientMemory;
488 }
489 else
490 {
491 for( i=0; i < guidVector->count; ++i )
492 {
493 newItems[i].name = guidVector->items[i].name;
494 if( guidVector->items[i].lpGUID == NULL )
495 {
496 newItems[i].lpGUID = NULL;
497 }
498 else
499 {
500 newItems[i].lpGUID = &newItems[i].guid;
501 memcpy( &newItems[i].guid, guidVector->items[i].lpGUID, sizeof(GUID) );
502 }
503 newItems[i].pnpInterface = guidVector->items[i].pnpInterface;
504 }
505
506 LocalFree( guidVector->items );
507 guidVector->items = newItems;
508 }
509
510 return result;
511 }
512
513 /*
514 it's safe to call DSDeviceNameAndGUIDVector multiple times
515 */
516 static PaError TerminateDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
517 {
518 PaError result = paNoError;
519
520 if( guidVector->items != NULL )
521 {
522 if( LocalFree( guidVector->items ) != NULL )
523 result = paInsufficientMemory; /** @todo this isn't the correct error to return from a deallocation failure */
524
525 guidVector->items = NULL;
526 }
527
528 return result;
529 }
530
531 /************************************************************************************
532 ** Collect preliminary device information during DirectSound enumeration
533 */
534 static BOOL CALLBACK CollectGUIDsProcW(LPGUID lpGUID,
535 LPCWSTR lpszDesc,
536 LPCWSTR lpszDrvName,
537 LPVOID lpContext )
538 {
539 DSDeviceNameAndGUIDVector *namesAndGUIDs = (DSDeviceNameAndGUIDVector*)lpContext;
540 PaError error;
541
542 (void) lpszDrvName; /* unused variable */
543
544 if( namesAndGUIDs->free == 0 )
545 {
546 error = ExpandDSDeviceNameAndGUIDVector( namesAndGUIDs );
547 if( error != paNoError )
548 {
549 namesAndGUIDs->enumerationError = error;
550 return FALSE;
551 }
552 }
553
554 /* Set GUID pointer, copy GUID to storage in DSDeviceNameAndGUIDVector. */
555 if( lpGUID == NULL )
556 {
557 namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = NULL;
558 }
559 else
560 {
561 namesAndGUIDs->items[namesAndGUIDs->count].lpGUID =
562 &namesAndGUIDs->items[namesAndGUIDs->count].guid;
563
564 memcpy( &namesAndGUIDs->items[namesAndGUIDs->count].guid, lpGUID, sizeof(GUID) );
565 }
566
567 namesAndGUIDs->items[namesAndGUIDs->count].name =
568 DuplicateDeviceNameString( namesAndGUIDs->allocations, lpszDesc );
569 if( namesAndGUIDs->items[namesAndGUIDs->count].name == NULL )
570 {
571 namesAndGUIDs->enumerationError = paInsufficientMemory;
572 return FALSE;
573 }
574
575 namesAndGUIDs->items[namesAndGUIDs->count].pnpInterface = 0;
576
577 ++namesAndGUIDs->count;
578 --namesAndGUIDs->free;
579
580 return TRUE;
581 }
582
583
584 #ifdef PAWIN_USE_WDMKS_DEVICE_INFO
585
586 static void *DuplicateWCharString( PaUtilAllocationGroup *allocations, wchar_t *source )
587 {
588 size_t len;
589 wchar_t *result;
590
591 len = wcslen( source );
592 result = (wchar_t*)PaUtil_GroupAllocateMemory( allocations, (long) ((len+1) * sizeof(wchar_t)) );
593 wcscpy( result, source );
594 return result;
595 }
596
597 static BOOL CALLBACK KsPropertySetEnumerateCallback( PDSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA data, LPVOID context )
598 {
599 int i;
600 DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs = (DSDeviceNamesAndGUIDs*)context;
601
602 /*
603 Apparently data->Interface can be NULL in some cases.
604 Possibly virtual devices without hardware.
605 So we check for NULLs now. See mailing list message November 10, 2012:
606 "[Portaudio] portaudio initialization crash in KsPropertySetEnumerateCallback(pa_win_ds.c)"
607 */
608 if( data->Interface )
609 {
610 if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_RENDER )
611 {
612 for( i=0; i < deviceNamesAndGUIDs->outputNamesAndGUIDs.count; ++i )
613 {
614 if( deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID
615 && memcmp( &data->DeviceId, deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )
616 {
617 deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].pnpInterface =
618 (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );
619 break;
620 }
621 }
622 }
623 else if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE )
624 {
625 for( i=0; i < deviceNamesAndGUIDs->inputNamesAndGUIDs.count; ++i )
626 {
627 if( deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID
628 && memcmp( &data->DeviceId, deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )
629 {
630 deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].pnpInterface =
631 (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );
632 break;
633 }
634 }
635 }
636 }
637
638 return TRUE;
639 }
640
641
642 static GUID pawin_CLSID_DirectSoundPrivate =
643 { 0x11ab3ec0, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };
644
645 static GUID pawin_DSPROPSETID_DirectSoundDevice =
646 { 0x84624f82, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };
647
648 static GUID pawin_IID_IKsPropertySet =
649 { 0x31efac30, 0x515c, 0x11d0, 0xa9, 0xaa, 0x00, 0xaa, 0x00, 0x61, 0xbe, 0x93 };
650
651
652 /*
653 FindDevicePnpInterfaces fills in the pnpInterface fields in deviceNamesAndGUIDs
654 with UNICODE file paths to the devices. The DS documentation mentions
655 at least two techniques by which these Interface paths can be found using IKsPropertySet on
656 the DirectSound class object. One is using the DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION
657 property, and the other is using DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE.
658 I tried both methods and only the second worked. I found two postings on the
659 net from people who had the same problem with the first method, so I think the method used here is
660 more common/likely to work. The problem is that IKsPropertySet_Get returns S_OK
661 but the fields of the device description are not filled in.
662
663 The mechanism we use works by registering an enumeration callback which is called for
664 every DSound device. Our callback searches for a device in our deviceNamesAndGUIDs list
665 with the matching GUID and copies the pointer to the Interface path.
666 Note that we could have used this enumeration callback to perform the original
667 device enumeration, however we choose not to so we can disable this step easily.
668
669 Apparently the IKsPropertySet mechanism was added in DirectSound 9c 2004
670 http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.mmedia/2004-12/0099.html
671
672 -- rossb
673 */
674 static void FindDevicePnpInterfaces( DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs )
675 {
676 IClassFactory *pClassFactory;
677
678 if( paWinDsDSoundEntryPoints.DllGetClassObject(&pawin_CLSID_DirectSoundPrivate, &IID_IClassFactory, (PVOID *) &pClassFactory) == S_OK ){
679 IKsPropertySet *pPropertySet;
680 if( pClassFactory->lpVtbl->CreateInstance( pClassFactory, NULL, &pawin_IID_IKsPropertySet, (PVOID *) &pPropertySet) == S_OK ){
681
682 DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA data;
683 ULONG bytesReturned;
684
685 data.Callback = KsPropertySetEnumerateCallback;
686 data.Context = deviceNamesAndGUIDs;
687
688 IKsPropertySet_Get( pPropertySet,
689 &pawin_DSPROPSETID_DirectSoundDevice,
690 DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W,
691 NULL,
692 0,
693 &data,
694 sizeof(data),
695 &bytesReturned
696 );
697
698 IKsPropertySet_Release( pPropertySet );
699 }
700 pClassFactory->lpVtbl->Release( pClassFactory );
701 }
702
703 /*
704 The following code fragment, which I chose not to use, queries for the
705 device interface for a device with a specific GUID:
706
707 ULONG BytesReturned;
708 DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA Property;
709
710 memset (&Property, 0, sizeof(Property));
711 Property.DataFlow = DIRECTSOUNDDEVICE_DATAFLOW_RENDER;
712 Property.DeviceId = *lpGUID;
713
714 hr = IKsPropertySet_Get( pPropertySet,
715 &pawin_DSPROPSETID_DirectSoundDevice,
716 DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W,
717 NULL,
718 0,
719 &Property,
720 sizeof(Property),
721 &BytesReturned
722 );
723
724 if( hr == S_OK )
725 {
726 //pnpInterface = Property.Interface;
727 }
728 */
729 }
730 #endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
731
732
733 /*
734 GUIDs for emulated devices which we blacklist below.
735 are there more than two of them??
736 */
737
738 GUID IID_IRolandVSCEmulated1 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x01};
739 GUID IID_IRolandVSCEmulated2 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x02};
740
741
742 #define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ (13) /* must match array length below */
743 static double defaultSampleRateSearchOrder_[] =
744 { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
745 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
746
747 /************************************************************************************
748 ** Extract capabilities from an output device, and add it to the device info list
749 ** if successful. This function assumes that there is enough room in the
750 ** device info list to accommodate all entries.
751 **
752 ** The device will not be added to the device list if any errors are encountered.
753 */
754 static PaError AddOutputDeviceInfoFromDirectSound(
755 PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )
756 {
757 PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep;
758 PaWinDsDeviceInfo *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];
759 PaDeviceInfo *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;
760 HRESULT hr;
761 LPDIRECTSOUND lpDirectSound;
762 DSCAPS caps;
763 int deviceOK = TRUE;
764 PaError result = paNoError;
765 int i;
766
767 /* Copy GUID to the device info structure. Set pointer. */
768 if( lpGUID == NULL )
769 {
770 winDsDeviceInfo->lpGUID = NULL;
771 }
772 else
773 {
774 memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
775 winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
776 }
777
778 if( lpGUID )
779 {
780 if (IsEqualGUID (&IID_IRolandVSCEmulated1,lpGUID) ||
781 IsEqualGUID (&IID_IRolandVSCEmulated2,lpGUID) )
782 {
783 PA_DEBUG(("BLACKLISTED: %s \n",name));
784 return paNoError;
785 }
786 }
787
788 /* Create a DirectSound object for the specified GUID
789 Note that using CoCreateInstance doesn't work on windows CE.
790 */
791 hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &lpDirectSound, NULL );
792
793 /** try using CoCreateInstance because DirectSoundCreate was hanging under
794 some circumstances - note this was probably related to the
795 #define BOOL short bug which has now been fixed
796 @todo delete this comment and the following code once we've ensured
797 there is no bug.
798 */
799 /*
800 hr = CoCreateInstance( &CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER,
801 &IID_IDirectSound, (void**)&lpDirectSound );
802
803 if( hr == S_OK )
804 {
805 hr = IDirectSound_Initialize( lpDirectSound, lpGUID );
806 }
807 */
808
809 if( hr != DS_OK )
810 {
811 if (hr == DSERR_ALLOCATED)
812 PA_DEBUG(("AddOutputDeviceInfoFromDirectSound %s DSERR_ALLOCATED\n",name));
813 DBUG(("Cannot create DirectSound for %s. Result = 0x%x\n", name, hr ));
814 if (lpGUID)
815 DBUG(("%s's GUID: {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, 0x%x} \n",
816 name,
817 lpGUID->Data1,
818 lpGUID->Data2,
819 lpGUID->Data3,
820 lpGUID->Data4[0],
821 lpGUID->Data4[1],
822 lpGUID->Data4[2],
823 lpGUID->Data4[3],
824 lpGUID->Data4[4],
825 lpGUID->Data4[5],
826 lpGUID->Data4[6],
827 lpGUID->Data4[7]));
828
829 deviceOK = FALSE;
830 }
831 else
832 {
833 /* Query device characteristics. */
834 memset( &caps, 0, sizeof(caps) );
835 caps.dwSize = sizeof(caps);
836 hr = IDirectSound_GetCaps( lpDirectSound, &caps );
837 if( hr != DS_OK )
838 {
839 DBUG(("Cannot GetCaps() for DirectSound device %s. Result = 0x%x\n", name, hr ));
840 deviceOK = FALSE;
841 }
842 else
843 {
844
845 #if PA_USE_WMME
846 if( caps.dwFlags & DSCAPS_EMULDRIVER )
847 {
848 /* If WMME supported, then reject Emulated drivers because they are lousy. */
849 deviceOK = FALSE;
850 }
851 #endif
852
853 if( deviceOK )
854 {
855 deviceInfo->maxInputChannels = 0;
856 winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
857
858 /* DS output capabilities only indicate supported number of channels
859 using two flags which indicate mono and/or stereo.
860 We assume that stereo devices may support more than 2 channels
861 (as is the case with 5.1 devices for example) and so
862 set deviceOutputChannelCountIsKnown to 0 (unknown).
863 In this case OpenStream will try to open the device
864 when the user requests more than 2 channels, rather than
865 returning an error.
866 */
867 if( caps.dwFlags & DSCAPS_PRIMARYSTEREO )
868 {
869 deviceInfo->maxOutputChannels = 2;
870 winDsDeviceInfo->deviceOutputChannelCountIsKnown = 0;
871 }
872 else
873 {
874 deviceInfo->maxOutputChannels = 1;
875 winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
876 }
877
878 /* Guess channels count from speaker configuration. We do it only when
879 pnpInterface is NULL or when PAWIN_USE_WDMKS_DEVICE_INFO is undefined.
880 */
881 #ifdef PAWIN_USE_WDMKS_DEVICE_INFO
882 if( !pnpInterface )
883 #endif
884 {
885 DWORD spkrcfg;
886 if( SUCCEEDED(IDirectSound_GetSpeakerConfig( lpDirectSound, &spkrcfg )) )
887 {
888 int count = 0;
889 switch (DSSPEAKER_CONFIG(spkrcfg))
890 {
891 case DSSPEAKER_HEADPHONE: count = 2; break;
892 case DSSPEAKER_MONO: count = 1; break;
893 case DSSPEAKER_QUAD: count = 4; break;
894 case DSSPEAKER_STEREO: count = 2; break;
895 case DSSPEAKER_SURROUND: count = 4; break;
896 case DSSPEAKER_5POINT1: count = 6; break;
897 #ifndef DSSPEAKER_7POINT1
898 #define DSSPEAKER_7POINT1 0x00000007
899 #endif
900 case DSSPEAKER_7POINT1: count = 8; break;
901 #ifndef DSSPEAKER_7POINT1_SURROUND
902 #define DSSPEAKER_7POINT1_SURROUND 0x00000008
903 #endif
904 case DSSPEAKER_7POINT1_SURROUND: count = 8; break;
905 #ifndef DSSPEAKER_5POINT1_SURROUND
906 #define DSSPEAKER_5POINT1_SURROUND 0x00000009
907 #endif
908 case DSSPEAKER_5POINT1_SURROUND: count = 6; break;
909 }
910 if( count )
911 {
912 deviceInfo->maxOutputChannels = count;
913 winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
914 }
915 }
916 }
917
918 #ifdef PAWIN_USE_WDMKS_DEVICE_INFO
919 if( pnpInterface )
920 {
921 int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 0 );
922 if( count > 0 )
923 {
924 deviceInfo->maxOutputChannels = count;
925 winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
926 }
927 }
928 #endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
929
930 /* initialize defaultSampleRate */
931
932 if( caps.dwFlags & DSCAPS_CONTINUOUSRATE )
933 {
934 /* initialize to caps.dwMaxSecondarySampleRate incase none of the standard rates match */
935 deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
936
937 for( i = 0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
938 {
939 if( defaultSampleRateSearchOrder_[i] >= caps.dwMinSecondarySampleRate
940 && defaultSampleRateSearchOrder_[i] <= caps.dwMaxSecondarySampleRate )
941 {
942 deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[i];
943 break;
944 }
945 }
946 }
947 else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate )
948 {
949 if( caps.dwMinSecondarySampleRate == 0 )
950 {
951 /*
952 ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !!
953 ** But it supports continuous sampling.
954 ** So fake range of rates, and hope it really supports it.
955 */
956 deviceInfo->defaultSampleRate = 48000.0f; /* assume 48000 as the default */
957
958 DBUG(("PA - Reported rates both zero. Setting to fake values for device #%s\n", name ));
959 }
960 else
961 {
962 deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
963 }
964 }
965 else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) )
966 {
967 /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000.
968 ** But we know that they really support a range of rates!
969 ** So when we see a ridiculous set of rates, assume it is a range.
970 */
971 deviceInfo->defaultSampleRate = 48000.0f; /* assume 48000 as the default */
972 DBUG(("PA - Sample rate range used instead of two odd values for device #%s\n", name ));
973 }
974 else deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
975
976 //printf( "min %d max %d\n", caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate );
977 // dwFlags | DSCAPS_CONTINUOUSRATE
978
979 deviceInfo->defaultLowInputLatency = 0.;
980 deviceInfo->defaultHighInputLatency = 0.;
981
982 deviceInfo->defaultLowOutputLatency = PaWinDs_GetMinLatencySeconds( deviceInfo->defaultSampleRate );
983 deviceInfo->defaultHighOutputLatency = deviceInfo->defaultLowOutputLatency * 2;
984 }
985 }
986
987 IDirectSound_Release( lpDirectSound );
988 }
989
990 if( deviceOK )
991 {
992 deviceInfo->name = name;
993
994 if( lpGUID == NULL )
995 hostApi->info.defaultOutputDevice = hostApi->info.deviceCount;
996
997 hostApi->info.deviceCount++;
998 }
999
1000 return result;
1001 }
1002
1003
1004 /************************************************************************************
1005 ** Extract capabilities from an input device, and add it to the device info list
1006 ** if successful. This function assumes that there is enough room in the
1007 ** device info list to accommodate all entries.
1008 **
1009 ** The device will not be added to the device list if any errors are encountered.
1010 */
1011 static PaError AddInputDeviceInfoFromDirectSoundCapture(
1012 PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )
1013 {
1014 PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep;
1015 PaWinDsDeviceInfo *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];
1016 PaDeviceInfo *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;
1017 HRESULT hr;
1018 LPDIRECTSOUNDCAPTURE lpDirectSoundCapture;
1019 DSCCAPS caps;
1020 int deviceOK = TRUE;
1021 PaError result = paNoError;
1022
1023 /* Copy GUID to the device info structure. Set pointer. */
1024 if( lpGUID == NULL )
1025 {
1026 winDsDeviceInfo->lpGUID = NULL;
1027 }
1028 else
1029 {
1030 winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
1031 memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
1032 }
1033
1034 hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL );
1035
1036 /** try using CoCreateInstance because DirectSoundCreate was hanging under
1037 some circumstances - note this was probably related to the
1038 #define BOOL short bug which has now been fixed
1039 @todo delete this comment and the following code once we've ensured
1040 there is no bug.
1041 */
1042 /*
1043 hr = CoCreateInstance( &CLSID_DirectSoundCapture, NULL, CLSCTX_INPROC_SERVER,
1044 &IID_IDirectSoundCapture, (void**)&lpDirectSoundCapture );
1045 */
1046 if( hr != DS_OK )
1047 {
1048 DBUG(("Cannot create Capture for %s. Result = 0x%x\n", name, hr ));
1049 deviceOK = FALSE;
1050 }
1051 else
1052 {
1053 /* Query device characteristics. */
1054 memset( &caps, 0, sizeof(caps) );
1055 caps.dwSize = sizeof(caps);
1056 hr = IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps );
1057 if( hr != DS_OK )
1058 {
1059 DBUG(("Cannot GetCaps() for Capture device %s. Result = 0x%x\n", name, hr ));
1060 deviceOK = FALSE;
1061 }
1062 else
1063 {
1064 #if PA_USE_WMME
1065 if( caps.dwFlags & DSCAPS_EMULDRIVER )
1066 {
1067 /* If WMME supported, then reject Emulated drivers because they are lousy. */
1068 deviceOK = FALSE;
1069 }
1070 #endif
1071
1072 if( deviceOK )
1073 {
1074 deviceInfo->maxInputChannels = caps.dwChannels;
1075 winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
1076
1077 deviceInfo->maxOutputChannels = 0;
1078 winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
1079
1080 #ifdef PAWIN_USE_WDMKS_DEVICE_INFO
1081 if( pnpInterface )
1082 {
1083 int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 1 );
1084 if( count > 0 )
1085 {
1086 deviceInfo->maxInputChannels = count;
1087 winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
1088 }
1089 }
1090 #endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
1091
1092 /* constants from a WINE patch by Francois Gouget, see:
1093 http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
1094
1095 ---
1096 Date: Fri, 14 May 2004 10:38:12 +0200 (CEST)
1097 From: Francois Gouget <fgouget@ ... .fr>
1098 To: Ross Bencina <rbencina@ ... .au>
1099 Subject: Re: Permission to use wine 48/96 wave patch in BSD licensed library
1100
1101 [snip]
1102
1103 I give you permission to use the patch below under the BSD license.
1104 http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
1105
1106 [snip]
1107 */
1108 #ifndef WAVE_FORMAT_48M08
1109 #define WAVE_FORMAT_48M08 0x00001000 /* 48 kHz, Mono, 8-bit */
1110 #define WAVE_FORMAT_48S08 0x00002000 /* 48 kHz, Stereo, 8-bit */
1111 #define WAVE_FORMAT_48M16 0x00004000 /* 48 kHz, Mono, 16-bit */
1112 #define WAVE_FORMAT_48S16 0x00008000 /* 48 kHz, Stereo, 16-bit */
1113 #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
1114 #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
1115 #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
1116 #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
1117 #endif
1118
1119 /* defaultSampleRate */
1120 if( caps.dwChannels == 2 )
1121 {
1122 if( caps.dwFormats & WAVE_FORMAT_4S16 )
1123 deviceInfo->defaultSampleRate = 44100.0;
1124 else if( caps.dwFormats & WAVE_FORMAT_48S16 )
1125 deviceInfo->defaultSampleRate = 48000.0;
1126 else if( caps.dwFormats & WAVE_FORMAT_2S16 )
1127 deviceInfo->defaultSampleRate = 22050.0;
1128 else if( caps.dwFormats & WAVE_FORMAT_1S16 )
1129 deviceInfo->defaultSampleRate = 11025.0;
1130 else if( caps.dwFormats & WAVE_FORMAT_96S16 )
1131 deviceInfo->defaultSampleRate = 96000.0;
1132 else
1133 deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */
1134 }
1135 else if( caps.dwChannels == 1 )
1136 {
1137 if( caps.dwFormats & WAVE_FORMAT_4M16 )
1138 deviceInfo->defaultSampleRate = 44100.0;
1139 else if( caps.dwFormats & WAVE_FORMAT_48M16 )
1140 deviceInfo->defaultSampleRate = 48000.0;
1141 else if( caps.dwFormats & WAVE_FORMAT_2M16 )
1142 deviceInfo->defaultSampleRate = 22050.0;
1143 else if( caps.dwFormats & WAVE_FORMAT_1M16 )
1144 deviceInfo->defaultSampleRate = 11025.0;
1145 else if( caps.dwFormats & WAVE_FORMAT_96M16 )
1146 deviceInfo->defaultSampleRate = 96000.0;
1147 else
1148 deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */
1149 }
1150 else deviceInfo->defaultSampleRate = 48000.0; /* assume 48000 as the default */
1151
1152 deviceInfo->defaultLowInputLatency = PaWinDs_GetMinLatencySeconds( deviceInfo->defaultSampleRate );
1153 deviceInfo->defaultHighInputLatency = deviceInfo->defaultLowInputLatency * 2;
1154
1155 deviceInfo->defaultLowOutputLatency = 0.;
1156 deviceInfo->defaultHighOutputLatency = 0.;
1157 }
1158 }
1159
1160 IDirectSoundCapture_Release( lpDirectSoundCapture );
1161 }
1162
1163 if( deviceOK )
1164 {
1165 deviceInfo->name = name;
1166
1167 if( lpGUID == NULL )
1168 hostApi->info.defaultInputDevice = hostApi->info.deviceCount;
1169
1170 hostApi->info.deviceCount++;
1171 }
1172
1173 return result;
1174 }
1175
1176
1177 /***********************************************************************************/
1178 PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
1179 {
1180 PaError result = paNoError;
1181 int i, deviceCount;
1182 PaWinDsHostApiRepresentation *winDsHostApi;
1183 DSDeviceNamesAndGUIDs deviceNamesAndGUIDs;
1184 PaWinDsDeviceInfo *deviceInfoArray;
1185
1186 PaWinDs_InitializeDSoundEntryPoints();
1187
1188 /* initialise guid vectors so they can be safely deleted on error */
1189 deviceNamesAndGUIDs.winDsHostApi = NULL;
1190 deviceNamesAndGUIDs.inputNamesAndGUIDs.items = NULL;
1191 deviceNamesAndGUIDs.outputNamesAndGUIDs.items = NULL;
1192
1193 winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) );
1194 if( !winDsHostApi )
1195 {
1196 result = paInsufficientMemory;
1197 goto error;
1198 }
1199
1200 memset( winDsHostApi, 0, sizeof(PaWinDsHostApiRepresentation) ); /* ensure all fields are zeroed. especially winDsHostApi->allocations */
1201
1202 result = PaWinUtil_CoInitialize( paDirectSound, &winDsHostApi->comInitializationResult );
1203 if( result != paNoError )
1204 {
1205 goto error;
1206 }
1207
1208 winDsHostApi->allocations = PaUtil_CreateAllocationGroup();
1209 if( !winDsHostApi->allocations )
1210 {
1211 result = paInsufficientMemory;
1212 goto error;
1213 }
1214
1215 *hostApi = &winDsHostApi->inheritedHostApiRep;
1216 (*hostApi)->info.structVersion = 1;
1217 (*hostApi)->info.type = paDirectSound;
1218 (*hostApi)->info.name = "Windows DirectSound";
1219
1220 (*hostApi)->info.deviceCount = 0;
1221 (*hostApi)->info.defaultInputDevice = paNoDevice;
1222 (*hostApi)->info.defaultOutputDevice = paNoDevice;
1223
1224
1225 /* DSound - enumerate devices to count them and to gather their GUIDs */
1226
1227 result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs, winDsHostApi->allocations );
1228 if( result != paNoError )
1229 goto error;
1230
1231 result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs, winDsHostApi->allocations );
1232 if( result != paNoError )
1233 goto error;
1234
1235 paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW( (LPDSENUMCALLBACKW)CollectGUIDsProcW, (void *)&deviceNamesAndGUIDs.inputNamesAndGUIDs );
1236
1237 paWinDsDSoundEntryPoints.DirectSoundEnumerateW( (LPDSENUMCALLBACKW)CollectGUIDsProcW, (void *)&deviceNamesAndGUIDs.outputNamesAndGUIDs );
1238
1239 if( deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError != paNoError )
1240 {
1241 result = deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError;
1242 goto error;
1243 }
1244
1245 if( deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError != paNoError )
1246 {
1247 result = deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError;
1248 goto error;
1249 }
1250
1251 deviceCount = deviceNamesAndGUIDs.inputNamesAndGUIDs.count + deviceNamesAndGUIDs.outputNamesAndGUIDs.count;
1252
1253 #ifdef PAWIN_USE_WDMKS_DEVICE_INFO
1254 if( deviceCount > 0 )
1255 {
1256 deviceNamesAndGUIDs.winDsHostApi = winDsHostApi;
1257 FindDevicePnpInterfaces( &deviceNamesAndGUIDs );
1258 }
1259 #endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
1260
1261 if( deviceCount > 0 )
1262 {
1263 /* allocate array for pointers to PaDeviceInfo structs */
1264 (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
1265 winDsHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );
1266 if( !(*hostApi)->deviceInfos )
1267 {
1268 result = paInsufficientMemory;
1269 goto error;
1270 }
1271
1272 /* allocate all PaDeviceInfo structs in a contiguous block */
1273 deviceInfoArray = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory(
1274 winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount );
1275 if( !deviceInfoArray )
1276 {
1277 result = paInsufficientMemory;
1278 goto error;
1279 }
1280
1281 for( i=0; i < deviceCount; ++i )
1282 {
1283 PaDeviceInfo *deviceInfo = &deviceInfoArray[i].inheritedDeviceInfo;
1284 deviceInfo->structVersion = 2;
1285 deviceInfo->hostApi = hostApiIndex;
1286 deviceInfo->name = 0;
1287 (*hostApi)->deviceInfos[i] = deviceInfo;
1288 }
1289
1290 for( i=0; i < deviceNamesAndGUIDs.inputNamesAndGUIDs.count; ++i )
1291 {
1292 result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi,
1293 deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].name,
1294 deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].lpGUID,
1295 deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].pnpInterface );
1296 if( result != paNoError )
1297 goto error;
1298 }
1299
1300 for( i=0; i < deviceNamesAndGUIDs.outputNamesAndGUIDs.count; ++i )
1301 {
1302 result = AddOutputDeviceInfoFromDirectSound( winDsHostApi,
1303 deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].name,
1304 deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].lpGUID,
1305 deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].pnpInterface );
1306 if( result != paNoError )
1307 goto error;
1308 }
1309 }
1310
1311 result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );
1312 if( result != paNoError )
1313 goto error;
1314
1315 result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );
1316 if( result != paNoError )
1317 goto error;
1318
1319
1320 (*hostApi)->Terminate = Terminate;
1321 (*hostApi)->OpenStream = OpenStream;
1322 (*hostApi)->IsFormatSupported = IsFormatSupported;
1323
1324 PaUtil_InitializeStreamInterface( &winDsHostApi->callbackStreamInterface, CloseStream, StartStream,
1325 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
1326 GetStreamTime, GetStreamCpuLoad,
1327 PaUtil_DummyRead, PaUtil_DummyWrite,
1328 PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
1329
1330 PaUtil_InitializeStreamInterface( &winDsHostApi->blockingStreamInterface, CloseStream, StartStream,
1331 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
1332 GetStreamTime, PaUtil_DummyGetCpuLoad,
1333 ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
1334
1335 return result;
1336
1337 error:
1338 TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );
1339 TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );
1340
1341 Terminate( (struct PaUtilHostApiRepresentation *)winDsHostApi );
1342
1343 return result;
1344 }
1345
1346
1347 /***********************************************************************************/
1348 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
1349 {
1350 PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
1351
1352 if( winDsHostApi ){
1353 if( winDsHostApi->allocations )
1354 {
1355 PaUtil_FreeAllAllocations( winDsHostApi->allocations );
1356 PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );
1357 }
1358
1359 PaWinUtil_CoUninitialize( paDirectSound, &winDsHostApi->comInitializationResult );
1360
1361 PaUtil_FreeMemory( winDsHostApi );
1362 }
1363
1364 PaWinDs_TerminateDSoundEntryPoints();
1365 }
1366
1367 static PaError ValidateWinDirectSoundSpecificStreamInfo(
1368 const PaStreamParameters *streamParameters,
1369 const PaWinDirectSoundStreamInfo *streamInfo )
1370 {
1371 if( streamInfo )
1372 {
1373 if( streamInfo->size != sizeof( PaWinDirectSoundStreamInfo )
1374 || streamInfo->version != 2 )
1375 {
1376 return paIncompatibleHostApiSpecificStreamInfo;
1377 }
1378
1379 if( streamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )
1380 {
1381 if( streamInfo->framesPerBuffer <= 0 )
1382 return paIncompatibleHostApiSpecificStreamInfo;
1383
1384 }
1385 }
1386
1387 return paNoError;
1388 }
1389
1390 /***********************************************************************************/
1391 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
1392 const PaStreamParameters *inputParameters,
1393 const PaStreamParameters *outputParameters,
1394 double sampleRate )
1395 {
1396 PaError result;
1397 PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;
1398 PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
1399 int inputChannelCount, outputChannelCount;
1400 PaSampleFormat inputSampleFormat, outputSampleFormat;
1401 PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;
1402
1403 if( inputParameters )
1404 {
1405 inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];
1406 inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;
1407
1408 inputChannelCount = inputParameters->channelCount;
1409 inputSampleFormat = inputParameters->sampleFormat;
1410
1411 /* unless alternate device specification is supported, reject the use of
1412 paUseHostApiSpecificDeviceSpecification */
1413
1414 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
1415 return paInvalidDevice;
1416
1417 /* check that input device can support inputChannelCount */
1418 if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown
1419 && inputChannelCount > inputDeviceInfo->maxInputChannels )
1420 return paInvalidChannelCount;
1421
1422 /* validate inputStreamInfo */
1423 inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
1424 result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );
1425 if( result != paNoError ) return result;
1426 }
1427 else
1428 {
1429 inputChannelCount = 0;
1430 }
1431
1432 if( outputParameters )
1433 {
1434 outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];
1435 outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;
1436
1437 outputChannelCount = outputParameters->channelCount;
1438 outputSampleFormat = outputParameters->sampleFormat;
1439
1440 /* unless alternate device specification is supported, reject the use of
1441 paUseHostApiSpecificDeviceSpecification */
1442
1443 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
1444 return paInvalidDevice;
1445
1446 /* check that output device can support inputChannelCount */
1447 if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown
1448 && outputChannelCount > outputDeviceInfo->maxOutputChannels )
1449 return paInvalidChannelCount;
1450
1451 /* validate outputStreamInfo */
1452 outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
1453 result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );
1454 if( result != paNoError ) return result;
1455 }
1456 else
1457 {
1458 outputChannelCount = 0;
1459 }
1460
1461 /*
1462 IMPLEMENT ME:
1463
1464 - if a full duplex stream is requested, check that the combination
1465 of input and output parameters is supported if necessary
1466
1467 - check that the device supports sampleRate
1468
1469 Because the buffer adapter handles conversion between all standard
1470 sample formats, the following checks are only required if paCustomFormat
1471 is implemented, or under some other unusual conditions.
1472
1473 - check that input device can support inputSampleFormat, or that
1474 we have the capability to convert from outputSampleFormat to
1475 a native format
1476
1477 - check that output device can support outputSampleFormat, or that
1478 we have the capability to convert from outputSampleFormat to
1479 a native format
1480 */
1481
1482 return paFormatIsSupported;
1483 }
1484
1485
1486 #ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
1487 static HRESULT InitFullDuplexInputOutputBuffers( PaWinDsStream *stream,
1488 PaWinDsDeviceInfo *inputDevice,
1489 PaSampleFormat hostInputSampleFormat,
1490 WORD inputChannelCount,
1491 int bytesPerInputBuffer,
1492 PaWinWaveFormatChannelMask inputChannelMask,
1493 PaWinDsDeviceInfo *outputDevice,
1494 PaSampleFormat hostOutputSampleFormat,
1495 WORD outputChannelCount,
1496 int bytesPerOutputBuffer,
1497 PaWinWaveFormatChannelMask outputChannelMask,
1498 unsigned long nFrameRate
1499 )
1500 {
1501 HRESULT hr;
1502 DSCBUFFERDESC captureDesc;
1503 PaWinWaveFormat captureWaveFormat;
1504 DSBUFFERDESC secondaryRenderDesc;
1505 PaWinWaveFormat renderWaveFormat;
1506 LPDIRECTSOUNDBUFFER8 pRenderBuffer8;
1507 LPDIRECTSOUNDCAPTUREBUFFER8 pCaptureBuffer8;
1508
1509 // capture buffer description
1510
1511 // only try wave format extensible. assume it's available on all ds 8 systems
1512 PaWin_InitializeWaveFormatExtensible( &captureWaveFormat, inputChannelCount,
1513 hostInputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostInputSampleFormat ),
1514 nFrameRate, inputChannelMask );
1515
1516 ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));
1517 captureDesc.dwSize = sizeof(DSCBUFFERDESC);
1518 captureDesc.dwFlags = 0;
1519 captureDesc.dwBufferBytes = bytesPerInputBuffer;
1520 captureDesc.lpwfxFormat = (WAVEFORMATEX*)&captureWaveFormat;
1521
1522 // render buffer description
1523
1524 PaWin_InitializeWaveFormatExtensible( &renderWaveFormat, outputChannelCount,
1525 hostOutputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostOutputSampleFormat ),
1526 nFrameRate, outputChannelMask );
1527
1528 ZeroMemory(&secondaryRenderDesc, sizeof(DSBUFFERDESC));
1529 secondaryRenderDesc.dwSize = sizeof(DSBUFFERDESC);
1530 secondaryRenderDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
1531 secondaryRenderDesc.dwBufferBytes = bytesPerOutputBuffer;
1532 secondaryRenderDesc.lpwfxFormat = (WAVEFORMATEX*)&renderWaveFormat;
1533
1534 /* note that we don't create a primary buffer here at all */
1535
1536 hr = paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8(
1537 inputDevice->lpGUID, outputDevice->lpGUID,
1538 &captureDesc, &secondaryRenderDesc,
1539 GetDesktopWindow(), /* see InitOutputBuffer() for a discussion of whether this is a good idea */
1540 DSSCL_EXCLUSIVE,
1541 &stream->pDirectSoundFullDuplex8,
1542 &pCaptureBuffer8,
1543 &pRenderBuffer8,
1544 NULL /* pUnkOuter must be NULL */
1545 );
1546
1547 if( hr == DS_OK )
1548 {
1549 PA_DEBUG(("DirectSoundFullDuplexCreate succeeded!\n"));
1550
1551 /* retrieve the pre ds 8 buffer interfaces which are used by the rest of the code */
1552
1553 hr = IUnknown_QueryInterface( pCaptureBuffer8, &IID_IDirectSoundCaptureBuffer, (LPVOID *)&stream->pDirectSoundInputBuffer );
1554
1555 if( hr == DS_OK )
1556 hr = IUnknown_QueryInterface( pRenderBuffer8, &IID_IDirectSoundBuffer, (LPVOID *)&stream->pDirectSoundOutputBuffer );
1557
1558 /* release the ds 8 interfaces, we don't need them */
1559 IUnknown_Release( pCaptureBuffer8 );
1560 IUnknown_Release( pRenderBuffer8 );
1561
1562 if( !stream->pDirectSoundInputBuffer || !stream->pDirectSoundOutputBuffer ){
1563 /* couldn't get pre ds 8 interfaces for some reason. clean up. */
1564 if( stream->pDirectSoundInputBuffer )
1565 {
1566 IUnknown_Release( stream->pDirectSoundInputBuffer );
1567 stream->pDirectSoundInputBuffer = NULL;
1568 }
1569
1570 if( stream->pDirectSoundOutputBuffer )
1571 {
1572 IUnknown_Release( stream->pDirectSoundOutputBuffer );
1573 stream->pDirectSoundOutputBuffer = NULL;
1574 }
1575
1576 IUnknown_Release( stream->pDirectSoundFullDuplex8 );
1577 stream->pDirectSoundFullDuplex8 = NULL;
1578 }
1579 }
1580 else
1581 {
1582 PA_DEBUG(("DirectSoundFullDuplexCreate failed. hr=%d\n", hr));
1583 }
1584
1585 return hr;
1586 }
1587 #endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
1588
1589
1590 static HRESULT InitInputBuffer( PaWinDsStream *stream,
1591 PaWinDsDeviceInfo *device,
1592 PaSampleFormat sampleFormat,
1593 unsigned long nFrameRate,
1594 WORD nChannels,
1595 int bytesPerBuffer,
1596 PaWinWaveFormatChannelMask channelMask )
1597 {
1598 DSCBUFFERDESC captureDesc;
1599 PaWinWaveFormat waveFormat;
1600 HRESULT result;
1601
1602 if( (result = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate(
1603 device->lpGUID, &stream->pDirectSoundCapture, NULL) ) != DS_OK ){
1604 ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));
1605 return result;
1606 }
1607
1608 // Setup the secondary buffer description
1609 ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));
1610 captureDesc.dwSize = sizeof(DSCBUFFERDESC);
1611 captureDesc.dwFlags = 0;
1612 captureDesc.dwBufferBytes = bytesPerBuffer;
1613 captureDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat;
1614
1615 // Create the capture buffer
1616
1617 // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX
1618 PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels,
1619 sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),
1620 nFrameRate, channelMask );
1621
1622 if( IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,
1623 &captureDesc, &stream->pDirectSoundInputBuffer, NULL) != DS_OK )
1624 {
1625 PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat,
1626 PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );
1627
1628 if ((result = IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,
1629 &captureDesc, &stream->pDirectSoundInputBuffer, NULL)) != DS_OK) return result;
1630 }
1631
1632 stream->readOffset = 0; // reset last read position to start of buffer
1633 return DS_OK;
1634 }
1635
1636
1637 static HRESULT InitOutputBuffer( PaWinDsStream *stream, PaWinDsDeviceInfo *device,
1638 PaSampleFormat sampleFormat, unsigned long nFrameRate,
1639 WORD nChannels, int bytesPerBuffer,
1640 PaWinWaveFormatChannelMask channelMask )
1641 {
1642 HRESULT result;
1643 HWND hWnd;
1644 HRESULT hr;
1645 PaWinWaveFormat waveFormat;
1646 DSBUFFERDESC primaryDesc;
1647 DSBUFFERDESC secondaryDesc;
1648
1649 if( (hr = paWinDsDSoundEntryPoints.DirectSoundCreate(
1650 device->lpGUID, &stream->pDirectSound, NULL )) != DS_OK ){
1651 ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));
1652 return hr;
1653 }
1654
1655 // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the
1656 // applications's window. Also if that window is closed before the Buffer is closed
1657 // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.)
1658 // So we will use GetDesktopWindow() which was suggested by Miller Puckette.
1659 // hWnd = GetForegroundWindow();
1660 //
1661 // FIXME: The example code I have on the net creates a hidden window that
1662 // is managed by our code - I think we should do that - one hidden
1663 // window for the whole of Pa_DS
1664 //
1665 hWnd = GetDesktopWindow();
1666
1667 // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz.
1668 // exclusive also prevents unexpected sounds from other apps during a performance.
1669 if ((hr = IDirectSound_SetCooperativeLevel( stream->pDirectSound,
1670 hWnd, DSSCL_EXCLUSIVE)) != DS_OK)
1671 {
1672 return hr;
1673 }
1674
1675 // -----------------------------------------------------------------------
1676 // Create primary buffer and set format just so we can specify our custom format.
1677 // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz.
1678 // Setup the primary buffer description
1679 ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC));
1680 primaryDesc.dwSize = sizeof(DSBUFFERDESC);
1681 primaryDesc.dwFlags = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth
1682 primaryDesc.dwBufferBytes = 0;
1683 primaryDesc.lpwfxFormat = NULL;
1684 // Create the buffer
1685 if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
1686 &primaryDesc, &stream->pDirectSoundPrimaryBuffer, NULL)) != DS_OK)
1687 goto error;
1688
1689 // Set the primary buffer's format
1690
1691 // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX
1692 PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels,
1693 sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),
1694 nFrameRate, channelMask );
1695
1696 if( IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat) != DS_OK )
1697 {
1698 PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat,
1699 PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );
1700
1701 if((result = IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat)) != DS_OK)
1702 goto error;
1703 }
1704
1705 // ----------------------------------------------------------------------
1706 // Setup the secondary buffer description
1707 ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC));
1708 secondaryDesc.dwSize = sizeof(DSBUFFERDESC);
1709 secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
1710 secondaryDesc.dwBufferBytes = bytesPerBuffer;
1711 secondaryDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat; /* waveFormat contains whatever format was negotiated for the primary buffer above */
1712 // Create the secondary buffer
1713 if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
1714 &secondaryDesc, &stream->pDirectSoundOutputBuffer, NULL)) != DS_OK)
1715 goto error;
1716
1717 return DS_OK;
1718
1719 error:
1720
1721 if( stream->pDirectSoundPrimaryBuffer )
1722 {
1723 IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
1724 stream->pDirectSoundPrimaryBuffer = NULL;
1725 }
1726
1727 return result;
1728 }
1729
1730
1731 static void CalculateBufferSettings( unsigned long *hostBufferSizeFrames,
1732 unsigned long *pollingPeriodFrames,
1733 int isFullDuplex,
1734 unsigned long suggestedInputLatencyFrames,
1735 unsigned long suggestedOutputLatencyFrames,
1736 double sampleRate, unsigned long userFramesPerBuffer )
1737 {
1738 unsigned long minimumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MINIMUM_POLLING_PERIOD_SECONDS);
1739 unsigned long maximumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS);
1740 unsigned long pollingJitterFrames = (unsigned long)(sampleRate * PA_DS_POLLING_JITTER_SECONDS);
1741
1742 if( userFramesPerBuffer == paFramesPerBufferUnspecified )
1743 {
1744 unsigned long targetBufferingLatencyFrames = max( suggestedInputLatencyFrames, suggestedOutputLatencyFrames );
1745
1746 *pollingPeriodFrames = targetBufferingLatencyFrames / 4;
1747 if( *pollingPeriodFrames < minimumPollingPeriodFrames )
1748 {
1749 *pollingPeriodFrames = minimumPollingPeriodFrames;
1750 }
1751 else if( *pollingPeriodFrames > maximumPollingPeriodFrames )
1752 {
1753 *pollingPeriodFrames = maximumPollingPeriodFrames;
1754 }
1755
1756 *hostBufferSizeFrames = *pollingPeriodFrames
1757 + max( *pollingPeriodFrames + pollingJitterFrames, targetBufferingLatencyFrames);
1758 }
1759 else
1760 {
1761 unsigned long targetBufferingLatencyFrames = suggestedInputLatencyFrames;
1762 if( isFullDuplex )
1763 {
1764 /* In full duplex streams we know that the buffer adapter adds userFramesPerBuffer
1765 extra fixed latency. so we subtract it here as a fixed latency before computing
1766 the buffer size. being careful not to produce an unrepresentable negative result.
1767
1768 Note: this only works as expected if output latency is greater than input latency.
1769 Otherwise we use input latency anyway since we do max(in,out).
1770 */
1771
1772 if( userFramesPerBuffer < suggestedOutputLatencyFrames )
1773 {
1774 unsigned long adjustedSuggestedOutputLatencyFrames =
1775 suggestedOutputLatencyFrames - userFramesPerBuffer;
1776
1777 /* maximum of input and adjusted output suggested latency */
1778 if( adjustedSuggestedOutputLatencyFrames > targetBufferingLatencyFrames )
1779 targetBufferingLatencyFrames = adjustedSuggestedOutputLatencyFrames;
1780 }
1781 }
1782 else
1783 {
1784 /* maximum of input and output suggested latency */
1785 if( suggestedOutputLatencyFrames > suggestedInputLatencyFrames )
1786 targetBufferingLatencyFrames = suggestedOutputLatencyFrames;
1787 }
1788
1789 *hostBufferSizeFrames = userFramesPerBuffer
1790 + max( userFramesPerBuffer + pollingJitterFrames, targetBufferingLatencyFrames);
1791
1792 *pollingPeriodFrames = max( max(1, userFramesPerBuffer / 4), targetBufferingLatencyFrames / 16 );
1793
1794 if( *pollingPeriodFrames > maximumPollingPeriodFrames )
1795 {
1796 *pollingPeriodFrames = maximumPollingPeriodFrames;
1797 }
1798 }
1799 }
1800
1801
1802 static void CalculatePollingPeriodFrames( unsigned long hostBufferSizeFrames,
1803 unsigned long *pollingPeriodFrames,
1804 double sampleRate, unsigned long userFramesPerBuffer )
1805 {
1806 unsigned long minimumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MINIMUM_POLLING_PERIOD_SECONDS);
1807 unsigned long maximumPollingPeriodFrames = (unsigned long)(sampleRate * PA_DS_MAXIMUM_POLLING_PERIOD_SECONDS);
1808 unsigned long pollingJitterFrames = (unsigned long)(sampleRate * PA_DS_POLLING_JITTER_SECONDS);
1809
1810 *pollingPeriodFrames = max( max(1, userFramesPerBuffer / 4), hostBufferSizeFrames / 16 );
1811
1812 if( *pollingPeriodFrames > maximumPollingPeriodFrames )
1813 {
1814 *pollingPeriodFrames = maximumPollingPeriodFrames;
1815 }
1816 }
1817
1818
1819 static void SetStreamInfoLatencies( PaWinDsStream *stream,
1820 unsigned long userFramesPerBuffer,
1821 unsigned long pollingPeriodFrames,
1822 double sampleRate )
1823 {
1824 /* compute the stream info actual latencies based on framesPerBuffer, polling period, hostBufferSizeFrames,
1825 and the configuration of the buffer processor */
1826
1827 unsigned long effectiveFramesPerBuffer = (userFramesPerBuffer == paFramesPerBufferUnspecified)
1828 ? pollingPeriodFrames
1829 : userFramesPerBuffer;
1830
1831 if( stream->bufferProcessor.inputChannelCount > 0 )
1832 {
1833 /* stream info input latency is the minimum buffering latency
1834 (unlike suggested and default which are *maximums*) */
1835 stream->streamRepresentation.streamInfo.inputLatency =
1836 (double)(PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor)
1837 + effectiveFramesPerBuffer) / sampleRate;
1838 }
1839 else
1840 {
1841 stream->streamRepresentation.streamInfo.inputLatency = 0;
1842 }
1843
1844 if( stream->bufferProcessor.outputChannelCount > 0 )
1845 {
1846 stream->streamRepresentation.streamInfo.outputLatency =
1847 (double)(PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor)
1848 + (stream->hostBufferSizeFrames - effectiveFramesPerBuffer)) / sampleRate;
1849 }
1850 else
1851 {
1852 stream->streamRepresentation.streamInfo.outputLatency = 0;
1853 }
1854 }
1855
1856
1857 /***********************************************************************************/
1858 /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
1859
1860 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
1861 PaStream** s,
1862 const PaStreamParameters *inputParameters,
1863 const PaStreamParameters *outputParameters,
1864 double sampleRate,
1865 unsigned long framesPerBuffer,
1866 PaStreamFlags streamFlags,
1867 PaStreamCallback *streamCallback,
1868 void *userData )
1869 {
1870 PaError result = paNoError;
1871 PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
1872 PaWinDsStream *stream = 0;
1873 int bufferProcessorIsInitialized = 0;
1874 int streamRepresentationIsInitialized = 0;
1875 PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;
1876 PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
1877 int inputChannelCount, outputChannelCount;
1878 PaSampleFormat inputSampleFormat, outputSampleFormat;
1879 PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
1880 int userRequestedHostInputBufferSizeFrames = 0;
1881 int userRequestedHostOutputBufferSizeFrames = 0;
1882 unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames;
1883 PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;
1884 PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;
1885 unsigned long pollingPeriodFrames = 0;
1886
1887 if( inputParameters )
1888 {
1889 inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];
1890 inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;
1891
1892 inputChannelCount = inputParameters->channelCount;
1893 inputSampleFormat = inputParameters->sampleFormat;
1894 suggestedInputLatencyFrames = (unsigned long)(inputParameters->suggestedLatency * sampleRate);
1895
1896 /* IDEA: the following 3 checks could be performed by default by pa_front
1897 unless some flag indicated otherwise */
1898
1899 /* unless alternate device specification is supported, reject the use of
1900 paUseHostApiSpecificDeviceSpecification */
1901 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
1902 return paInvalidDevice;
1903
1904 /* check that input device can support inputChannelCount */
1905 if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown
1906 && inputChannelCount > inputDeviceInfo->maxInputChannels )
1907 return paInvalidChannelCount;
1908
1909 /* validate hostApiSpecificStreamInfo */
1910 inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
1911 result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );
1912 if( result != paNoError ) return result;
1913
1914 if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )
1915 userRequestedHostInputBufferSizeFrames = inputStreamInfo->framesPerBuffer;
1916
1917 if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseChannelMask )
1918 inputChannelMask = inputStreamInfo->channelMask;
1919 else
1920 inputChannelMask = PaWin_DefaultChannelMask( inputChannelCount );
1921 }
1922 else
1923 {
1924 inputChannelCount = 0;
1925 inputSampleFormat = 0;
1926 suggestedInputLatencyFrames = 0;
1927 }
1928
1929
1930 if( outputParameters )
1931 {
1932 outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];
1933 outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;
1934
1935 outputChannelCount = outputParameters->channelCount;
1936 outputSampleFormat = outputParameters->sampleFormat;
1937 suggestedOutputLatencyFrames = (unsigned long)(outputParameters->suggestedLatency * sampleRate);
1938
1939 /* unless alternate device specification is supported, reject the use of
1940 paUseHostApiSpecificDeviceSpecification */
1941 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
1942 return paInvalidDevice;
1943
1944 /* check that output device can support outputChannelCount */
1945 if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown
1946 && outputChannelCount > outputDeviceInfo->maxOutputChannels )
1947 return paInvalidChannelCount;
1948
1949 /* validate hostApiSpecificStreamInfo */
1950 outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
1951 result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );
1952 if( result != paNoError ) return result;
1953
1954 if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseLowLevelLatencyParameters )
1955 userRequestedHostOutputBufferSizeFrames = outputStreamInfo->framesPerBuffer;
1956
1957 if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseChannelMask )
1958 outputChannelMask = outputStreamInfo->channelMask;
1959 else
1960 outputChannelMask = PaWin_DefaultChannelMask( outputChannelCount );
1961 }
1962 else
1963 {
1964 outputChannelCount = 0;
1965 outputSampleFormat = 0;
1966 suggestedOutputLatencyFrames = 0;
1967 }
1968
1969 /*
1970 If low level host buffer size is specified for both input and output
1971 the current code requires the sizes to match.
1972 */
1973
1974 if( (userRequestedHostInputBufferSizeFrames > 0 && userRequestedHostOutputBufferSizeFrames > 0)
1975 && userRequestedHostInputBufferSizeFrames != userRequestedHostOutputBufferSizeFrames )
1976 return paIncompatibleHostApiSpecificStreamInfo;
1977
1978
1979
1980 /*
1981 IMPLEMENT ME:
1982
1983 ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() )
1984
1985 - check that input device can support inputSampleFormat, or that
1986 we have the capability to convert from outputSampleFormat to
1987 a native format
1988
1989 - check that output device can support outputSampleFormat, or that
1990 we have the capability to convert from outputSampleFormat to
1991 a native format
1992
1993 - if a full duplex stream is requested, check that the combination
1994 of input and output parameters is supported
1995
1996 - check that the device supports sampleRate
1997
1998 - alter sampleRate to a close allowable rate if possible / necessary
1999
2000 - validate suggestedInputLatency and suggestedOutputLatency parameters,
2001 use default values where necessary
2002 */
2003
2004
2005 /* validate platform specific flags */
2006 if( (streamFlags & paPlatformSpecificFlags) != 0 )
2007 return paInvalidFlag; /* unexpected platform specific flag */
2008
2009
2010 stream = (PaWinDsStream*)PaUtil_AllocateMemory( sizeof(PaWinDsStream) );
2011 if( !stream )
2012 {
2013 result = paInsufficientMemory;
2014 goto error;
2015 }
2016
2017 memset( stream, 0, sizeof(PaWinDsStream) ); /* initialize all stream variables to 0 */
2018
2019 if( streamCallback )
2020 {
2021 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
2022 &winDsHostApi->callbackStreamInterface, streamCallback, userData );
2023 }
2024 else
2025 {
2026 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
2027 &winDsHostApi->blockingStreamInterface, streamCallback, userData );
2028 }
2029
2030 streamRepresentationIsInitialized = 1;
2031
2032 stream->streamFlags = streamFlags;
2033
2034 PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
2035
2036
2037 if( inputParameters )
2038 {
2039 /* IMPLEMENT ME - establish which host formats are available */
2040 PaSampleFormat nativeInputFormats = paInt16;
2041 /* PaSampleFormat nativeFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; */
2042
2043 hostInputSampleFormat =
2044 PaUtil_SelectClosestAvailableFormat( nativeInputFormats, inputParameters->sampleFormat );
2045 }
2046 else
2047 {
2048 hostInputSampleFormat = 0;
2049 }
2050
2051 if( outputParameters )
2052 {
2053 /* IMPLEMENT ME - establish which host formats are available */
2054 PaSampleFormat nativeOutputFormats = paInt16;
2055 /* PaSampleFormat nativeOutputFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; */
2056
2057 hostOutputSampleFormat =
2058 PaUtil_SelectClosestAvailableFormat( nativeOutputFormats, outputParameters->sampleFormat );
2059 }
2060 else
2061 {
2062 hostOutputSampleFormat = 0;
2063 }
2064
2065 result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
2066 inputChannelCount, inputSampleFormat, hostInputSampleFormat,
2067 outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
2068 sampleRate, streamFlags, framesPerBuffer,
2069 0, /* ignored in paUtilVariableHostBufferSizePartialUsageAllowed mode. */
2070 /* This next mode is required because DS can split the host buffer when it wraps around. */
2071 paUtilVariableHostBufferSizePartialUsageAllowed,
2072 streamCallback, userData );
2073 if( result != paNoError )
2074 goto error;
2075
2076 bufferProcessorIsInitialized = 1;
2077
2078
2079 /* DirectSound specific initialization */
2080 {
2081 HRESULT hr;
2082 unsigned long integerSampleRate = (unsigned long) (sampleRate + 0.5);
2083
2084 stream->processingCompleted = CreateEvent( NULL, /* bManualReset = */ TRUE, /* bInitialState = */ FALSE, NULL );
2085 if( stream->processingCompleted == NULL )
2086 {
2087 result = paInsufficientMemory;
2088 goto error;
2089 }
2090
2091 #ifdef PA_WIN_DS_USE_WMME_TIMER
2092 stream->timerID = 0;
2093 #endif
2094
2095 #ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
2096 stream->waitableTimer = (HANDLE)CreateWaitableTimer( 0, FALSE, NULL );
2097 if( stream->waitableTimer == NULL )
2098 {
2099 result = paUnanticipatedHostError;
2100 PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
2101 goto error;
2102 }
2103 #endif
2104
2105 #ifndef PA_WIN_DS_USE_WMME_TIMER
2106 stream->processingThreadCompleted = CreateEvent( NULL, /* bManualReset = */ TRUE, /* bInitialState = */ FALSE, NULL );
2107 if( stream->processingThreadCompleted == NULL )
2108 {
2109 result = paUnanticipatedHostError;
2110 PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
2111 goto error;
2112 }
2113 #endif
2114
2115 /* set up i/o parameters */
2116
2117 if( userRequestedHostInputBufferSizeFrames > 0 || userRequestedHostOutputBufferSizeFrames > 0 )
2118 {
2119 /* use low level parameters */
2120
2121 /* since we use the same host buffer size for input and output
2122 we choose the highest user specified value.
2123 */
2124 stream->hostBufferSizeFrames = max( userRequestedHostInputBufferSizeFrames, userRequestedHostOutputBufferSizeFrames );
2125
2126 CalculatePollingPeriodFrames(
2127 stream->hostBufferSizeFrames, &pollingPeriodFrames,
2128 sampleRate, framesPerBuffer );
2129 }
2130 else
2131 {
2132 CalculateBufferSettings( (unsigned long*)&stream->hostBufferSizeFrames, &pollingPeriodFrames,
2133 /* isFullDuplex = */ (inputParameters && outputParameters),
2134 suggestedInputLatencyFrames,
2135 suggestedOutputLatencyFrames,
2136 sampleRate, framesPerBuffer );
2137 }
2138
2139 stream->pollingPeriodSeconds = pollingPeriodFrames / sampleRate;
2140
2141 DBUG(("DirectSound host buffer size frames: %d, polling period seconds: %f, @ sr: %f\n",
2142 stream->hostBufferSizeFrames, stream->pollingPeriodSeconds, sampleRate ));
2143
2144
2145 /* ------------------ OUTPUT */
2146 if( outputParameters )
2147 {
2148 LARGE_INTEGER counterFrequency;
2149
2150 /*
2151 PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ outputParameters->device ];
2152 DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", outputParameters->device));
2153 */
2154
2155 int sampleSizeBytes = Pa_GetSampleSize(hostOutputSampleFormat);
2156 stream->outputFrameSizeBytes = outputParameters->channelCount * sampleSizeBytes;
2157
2158 stream->outputBufferSizeBytes = stream->hostBufferSizeFrames * stream->outputFrameSizeBytes;
2159 if( stream->outputBufferSizeBytes < DSBSIZE_MIN )
2160 {
2161 result = paBufferTooSmall;
2162 goto error;
2163 }
2164 else if( stream->outputBufferSizeBytes > DSBSIZE_MAX )
2165 {
2166 result = paBufferTooBig;
2167 goto error;
2168 }
2169
2170 /* Calculate value used in latency calculation to avoid real-time divides. */
2171 stream->secondsPerHostByte = 1.0 /
2172 (stream->bufferProcessor.bytesPerHostOutputSample *
2173 outputChannelCount * sampleRate);
2174
2175 stream->outputIsRunning = FALSE;
2176 stream->outputUnderflowCount = 0;
2177
2178 /* perfCounterTicksPerBuffer is used by QueryOutputSpace for overflow detection */
2179 if( QueryPerformanceFrequency( &counterFrequency ) )
2180 {
2181 stream->perfCounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * stream->hostBufferSizeFrames) / integerSampleRate;
2182 }
2183 else
2184 {
2185 stream->perfCounterTicksPerBuffer.QuadPart = 0;
2186 }
2187 }
2188
2189 /* ------------------ INPUT */
2190 if( inputParameters )
2191 {
2192 /*
2193 PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ inputParameters->device ];
2194 DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", inputParameters->device));
2195 */
2196
2197 int sampleSizeBytes = Pa_GetSampleSize(hostInputSampleFormat);
2198 stream->inputFrameSizeBytes = inputParameters->channelCount * sampleSizeBytes;
2199
2200 stream->inputBufferSizeBytes = stream->hostBufferSizeFrames * stream->inputFrameSizeBytes;
2201 if( stream->inputBufferSizeBytes < DSBSIZE_MIN )
2202 {
2203 result = paBufferTooSmall;
2204 goto error;
2205 }
2206 else if( stream->inputBufferSizeBytes > DSBSIZE_MAX )
2207 {
2208 result = paBufferTooBig;
2209 goto error;
2210 }
2211 }
2212
2213 /* open/create the DirectSound buffers */
2214
2215 /* interface ptrs should be zeroed when stream is zeroed. */
2216 assert( stream->pDirectSoundCapture == NULL );
2217 assert( stream->pDirectSoundInputBuffer == NULL );
2218 assert( stream->pDirectSound == NULL );
2219 assert( stream->pDirectSoundPrimaryBuffer == NULL );
2220 assert( stream->pDirectSoundOutputBuffer == NULL );
2221
2222
2223 if( inputParameters && outputParameters )
2224 {
2225 #ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
2226 /* try to use the full-duplex DX8 API to create the buffers.
2227 if that fails we fall back to the half-duplex API below */
2228
2229 hr = InitFullDuplexInputOutputBuffers( stream,
2230 (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],
2231 hostInputSampleFormat,
2232 (WORD)inputParameters->channelCount, stream->inputBufferSizeBytes,
2233 inputChannelMask,
2234 (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],
2235 hostOutputSampleFormat,
2236 (WORD)outputParameters->channelCount, stream->outputBufferSizeBytes,
2237 outputChannelMask,
2238 integerSampleRate
2239 );
2240 DBUG(("InitFullDuplexInputOutputBuffers() returns %x\n", hr));
2241 /* ignore any error returned by InitFullDuplexInputOutputBuffers.
2242 we retry opening the buffers below */
2243 #endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
2244 }
2245
2246 /* create half duplex buffers. also used for full-duplex streams which didn't
2247 succeed when using the full duplex API. that could happen because
2248 DX8 or greater isn't installed, the i/o devices aren't the same
2249 physical device. etc.
2250 */
2251
2252 if( outputParameters && !stream->pDirectSoundOutputBuffer )
2253 {
2254 hr = InitOutputBuffer( stream,
2255 (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],
2256 hostOutputSampleFormat,
2257 integerSampleRate,
2258 (WORD)outputParameters->channelCount, stream->outputBufferSizeBytes,
2259 outputChannelMask );
2260 DBUG(("InitOutputBuffer() returns %x\n", hr));
2261 if( hr != DS_OK )
2262 {
2263 result = paUnanticipatedHostError;
2264 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
2265 goto error;
2266 }
2267 }
2268
2269 if( inputParameters && !stream->pDirectSoundInputBuffer )
2270 {
2271 hr = InitInputBuffer( stream,
2272 (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],
2273 hostInputSampleFormat,
2274 integerSampleRate,
2275 (WORD)inputParameters->channelCount, stream->inputBufferSizeBytes,
2276 inputChannelMask );
2277 DBUG(("InitInputBuffer() returns %x\n", hr));
2278 if( hr != DS_OK )
2279 {
2280 ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));
2281 result = paUnanticipatedHostError;
2282 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
2283 goto error;
2284 }
2285 }
2286 }
2287
2288 SetStreamInfoLatencies( stream, framesPerBuffer, pollingPeriodFrames, sampleRate );
2289
2290 stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
2291
2292 *s = (PaStream*)stream;
2293
2294 return result;
2295
2296 error:
2297 if( stream )
2298 {
2299 if( stream->processingCompleted != NULL )
2300 CloseHandle( stream->processingCompleted );
2301
2302 #ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
2303 if( stream->waitableTimer != NULL )
2304 CloseHandle( stream->waitableTimer );
2305 #endif
2306
2307 #ifndef PA_WIN_DS_USE_WMME_TIMER
2308 if( stream->processingThreadCompleted != NULL )
2309 CloseHandle( stream->processingThreadCompleted );
2310 #endif
2311
2312 if( stream->pDirectSoundOutputBuffer )
2313 {
2314 IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
2315 IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );
2316 stream->pDirectSoundOutputBuffer = NULL;
2317 }
2318
2319 if( stream->pDirectSoundPrimaryBuffer )
2320 {
2321 IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
2322 stream->pDirectSoundPrimaryBuffer = NULL;
2323 }
2324
2325 if( stream->pDirectSoundInputBuffer )
2326 {
2327 IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
2328 IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );
2329 stream->pDirectSoundInputBuffer = NULL;
2330 }
2331
2332 if( stream->pDirectSoundCapture )
2333 {
2334 IDirectSoundCapture_Release( stream->pDirectSoundCapture );
2335 stream->pDirectSoundCapture = NULL;
2336 }
2337
2338 if( stream->pDirectSound )
2339 {
2340 IDirectSound_Release( stream->pDirectSound );
2341 stream->pDirectSound = NULL;
2342 }
2343
2344 #ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
2345 if( stream->pDirectSoundFullDuplex8 )
2346 {
2347 IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );
2348 stream->pDirectSoundFullDuplex8 = NULL;
2349 }
2350 #endif
2351 if( bufferProcessorIsInitialized )
2352 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
2353
2354 if( streamRepresentationIsInitialized )
2355 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
2356
2357 PaUtil_FreeMemory( stream );
2358 }
2359
2360 return result;
2361 }
2362
2363
2364 /************************************************************************************
2365 * Determine how much space can be safely written to in DS buffer.
2366 * Detect underflows and overflows.
2367 * Does not allow writing into safety gap maintained by DirectSound.
2368 */
2369 static HRESULT QueryOutputSpace( PaWinDsStream *stream, long *bytesEmpty )
2370 {
2371 HRESULT hr;
2372 DWORD playCursor;
2373 DWORD writeCursor;
2374 long numBytesEmpty;
2375 long playWriteGap;
2376 // Query to see how much room is in buffer.
2377 hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
2378 &playCursor, &writeCursor );
2379 if( hr != DS_OK )
2380 {
2381 return hr;
2382 }
2383
2384 // Determine size of gap between playIndex and WriteIndex that we cannot write into.
2385 playWriteGap = writeCursor - playCursor;
2386 if( playWriteGap < 0 ) playWriteGap += stream->outputBufferSizeBytes; // unwrap
2387
2388 /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */
2389 /* Attempt to detect playCursor wrap-around and correct it. */
2390 if( stream->outputIsRunning && (stream->perfCounterTicksPerBuffer.QuadPart != 0) )
2391 {
2392 /* How much time has elapsed since last check. */
2393 LARGE_INTEGER currentTime;
2394 LARGE_INTEGER elapsedTime;
2395 long bytesPlayed;
2396 long bytesExpected;
2397 long buffersWrapped;
2398
2399 QueryPerformanceCounter( &currentTime );
2400 elapsedTime.QuadPart = currentTime.QuadPart - stream->previousPlayTime.QuadPart;
2401 stream->previousPlayTime = currentTime;
2402
2403 /* How many bytes does DirectSound say have been played. */
2404 bytesPlayed = playCursor - stream->previousPlayCursor;
2405 if( bytesPlayed < 0 ) bytesPlayed += stream->outputBufferSizeBytes; // unwrap
2406 stream->previousPlayCursor = playCursor;
2407
2408 /* Calculate how many bytes we would have expected to been played by now. */
2409 bytesExpected = (long) ((elapsedTime.QuadPart * stream->outputBufferSizeBytes) / stream->perfCounterTicksPerBuffer.QuadPart);
2410 buffersWrapped = (bytesExpected - bytesPlayed) / stream->outputBufferSizeBytes;
2411 if( buffersWrapped > 0 )
2412 {
2413 playCursor += (buffersWrapped * stream->outputBufferSizeBytes);
2414 bytesPlayed += (buffersWrapped * stream->outputBufferSizeBytes);
2415 }
2416 }
2417 numBytesEmpty = playCursor - stream->outputBufferWriteOffsetBytes;
2418 if( numBytesEmpty < 0 ) numBytesEmpty += stream->outputBufferSizeBytes; // unwrap offset
2419
2420 /* Have we underflowed? */
2421 if( numBytesEmpty > (stream->outputBufferSizeBytes - playWriteGap) )
2422 {
2423 if( stream->outputIsRunning )
2424 {
2425 stream->outputUnderflowCount += 1;
2426 }
2427
2428 /*
2429 From MSDN:
2430 The write cursor indicates the position at which it is safe
2431 to write new data to the buffer. The write cursor always leads the
2432 play cursor, typically by about 15 milliseconds' worth of audio
2433 data.
2434 It is always safe to change data that is behind the position
2435 indicated by the lpdwCurrentPlayCursor parameter.
2436 */
2437
2438 stream->outputBufferWriteOffsetBytes = writeCursor;
2439 numBytesEmpty = stream->outputBufferSizeBytes - playWriteGap;
2440 }
2441 *bytesEmpty = numBytesEmpty;
2442 return hr;
2443 }
2444
2445 /***********************************************************************************/
2446 static int TimeSlice( PaWinDsStream *stream )
2447 {
2448 long numFrames = 0;
2449 long bytesEmpty = 0;
2450 long bytesFilled = 0;
2451 long bytesToXfer = 0;
2452 long framesToXfer = 0; /* the number of frames we'll process this tick */
2453 long numInFramesReady = 0;
2454 long numOutFramesReady = 0;
2455 long bytesProcessed;
2456 HRESULT hresult;
2457 double outputLatency = 0;
2458 double inputLatency = 0;
2459 PaStreamCallbackTimeInfo timeInfo = {0,0,0};
2460
2461 /* Input */
2462 LPBYTE lpInBuf1 = NULL;
2463 LPBYTE lpInBuf2 = NULL;
2464 DWORD dwInSize1 = 0;
2465 DWORD dwInSize2 = 0;
2466 /* Output */
2467 LPBYTE lpOutBuf1 = NULL;
2468 LPBYTE lpOutBuf2 = NULL;
2469 DWORD dwOutSize1 = 0;
2470 DWORD dwOutSize2 = 0;
2471
2472 /* How much input data is available? */
2473 if( stream->bufferProcessor.inputChannelCount > 0 )
2474 {
2475 HRESULT hr;
2476 DWORD capturePos;
2477 DWORD readPos;
2478 long filled = 0;
2479 // Query to see how much data is in buffer.
2480 // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly
2481 // so let's pass a pointer just to be safe.
2482 hr = IDirectSoundCaptureBuffer_GetCurrentPosition( stream->pDirectSoundInputBuffer, &capturePos, &readPos );
2483 if( hr == DS_OK )
2484 {
2485 filled = readPos - stream->readOffset;
2486 if( filled < 0 ) filled += stream->inputBufferSizeBytes; // unwrap offset
2487 bytesFilled = filled;
2488
2489 inputLatency = ((double)bytesFilled) * stream->secondsPerHostByte;
2490 }
2491 // FIXME: what happens if IDirectSoundCaptureBuffer_GetCurrentPosition fails?
2492
2493 framesToXfer = numInFramesReady = bytesFilled / stream->inputFrameSizeBytes;
2494
2495 /** @todo Check for overflow */
2496 }
2497
2498 /* How much output room is available? */
2499 if( stream->bufferProcessor.outputChannelCount > 0 )
2500 {
2501 UINT previousUnderflowCount = stream->outputUnderflowCount;
2502 QueryOutputSpace( stream, &bytesEmpty );
2503 framesToXfer = numOutFramesReady = bytesEmpty / stream->outputFrameSizeBytes;
2504
2505 /* Check for underflow */
2506 /* FIXME QueryOutputSpace should not adjust underflow count as a side effect.
2507 A query function should be a const operator on the stream and return a flag on underflow. */
2508 if( stream->outputUnderflowCount != previousUnderflowCount )
2509 stream->callbackFlags |= paOutputUnderflow;
2510
2511 /* We are about to compute audio into the first byte of empty space in the output buffer.
2512 This audio will reach the DAC after all of the current (non-empty) audio
2513 in the buffer has played. Therefore the output time is the current time
2514 plus the time it takes to play the non-empty bytes in the buffer,
2515 computed here:
2516 */
2517 outputLatency = ((double)(stream->outputBufferSizeBytes - bytesEmpty)) * stream->secondsPerHostByte;
2518 }
2519
2520 /* if it's a full duplex stream, set framesToXfer to the minimum of input and output frames ready */
2521 if( stream->bufferProcessor.inputChannelCount > 0 && stream->bufferProcessor.outputChannelCount > 0 )
2522 {
2523 framesToXfer = (numOutFramesReady < numInFramesReady) ? numOutFramesReady : numInFramesReady;
2524 }
2525
2526 if( framesToXfer > 0 )
2527 {
2528 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
2529
2530 /* The outputBufferDacTime parameter should indicates the time at which
2531 the first sample of the output buffer is heard at the DACs. */
2532 timeInfo.currentTime = PaUtil_GetTime();
2533
2534 PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, stream->callbackFlags );
2535 stream->callbackFlags = 0;
2536
2537 /* Input */
2538 if( stream->bufferProcessor.inputChannelCount > 0 )
2539 {
2540 timeInfo.inputBufferAdcTime = timeInfo.currentTime - inputLatency;
2541
2542 bytesToXfer = framesToXfer * stream->inputFrameSizeBytes;
2543 hresult = IDirectSoundCaptureBuffer_Lock ( stream->pDirectSoundInputBuffer,
2544 stream->readOffset, bytesToXfer,
2545 (void **) &lpInBuf1, &dwInSize1,
2546 (void **) &lpInBuf2, &dwInSize2, 0);
2547 if (hresult != DS_OK)
2548 {
2549 ERR_RPT(("DirectSound IDirectSoundCaptureBuffer_Lock failed, hresult = 0x%x\n",hresult));
2550 /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */
2551 PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */
2552 stream->callbackResult = paComplete;
2553 goto error2;
2554 }
2555
2556 numFrames = dwInSize1 / stream->inputFrameSizeBytes;
2557 PaUtil_SetInputFrameCount( &stream->bufferProcessor, numFrames );
2558 PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf1, 0 );
2559 /* Is input split into two regions. */
2560 if( dwInSize2 > 0 )
2561 {
2562 numFrames = dwInSize2 / stream->inputFrameSizeBytes;
2563 PaUtil_Set2ndInputFrameCount( &stream->bufferProcessor, numFrames );
2564 PaUtil_Set2ndInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf2, 0 );
2565 }
2566 }
2567
2568 /* Output */
2569 if( stream->bufferProcessor.outputChannelCount > 0 )
2570 {
2571 /*
2572 We don't currently add outputLatency here because it appears to produce worse
2573 results than not adding it. Need to do more testing to verify this.
2574 */
2575 /* timeInfo.outputBufferDacTime = timeInfo.currentTime + outputLatency; */
2576 timeInfo.outputBufferDacTime = timeInfo.currentTime;
2577
2578 bytesToXfer = framesToXfer * stream->outputFrameSizeBytes;
2579 hresult = IDirectSoundBuffer_Lock ( stream->pDirectSoundOutputBuffer,
2580 stream->outputBufferWriteOffsetBytes, bytesToXfer,
2581 (void **) &lpOutBuf1, &dwOutSize1,
2582 (void **) &lpOutBuf2, &dwOutSize2, 0);
2583 if (hresult != DS_OK)
2584 {
2585 ERR_RPT(("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n",hresult));
2586 /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */
2587 PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */
2588 stream->callbackResult = paComplete;
2589 goto error1;
2590 }
2591
2592 numFrames = dwOutSize1 / stream->outputFrameSizeBytes;
2593 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, numFrames );
2594 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf1, 0 );
2595
2596 /* Is output split into two regions. */
2597 if( dwOutSize2 > 0 )
2598 {
2599 numFrames = dwOutSize2 / stream->outputFrameSizeBytes;
2600 PaUtil_Set2ndOutputFrameCount( &stream->bufferProcessor, numFrames );
2601 PaUtil_Set2ndInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf2, 0 );
2602 }
2603 }
2604
2605 numFrames = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &stream->callbackResult );
2606 stream->framesWritten += numFrames;
2607
2608 if( stream->bufferProcessor.outputChannelCount > 0 )
2609 {
2610 /* FIXME: an underflow could happen here */
2611
2612 /* Update our buffer offset and unlock sound buffer */
2613 bytesProcessed = numFrames * stream->outputFrameSizeBytes;
2614 stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + bytesProcessed) % stream->outputBufferSizeBytes;
2615 IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2);
2616 }
2617
2618 error1:
2619 if( stream->bufferProcessor.inputChannelCount > 0 )
2620 {
2621 /* FIXME: an overflow could happen here */
2622
2623 /* Update our buffer offset and unlock sound buffer */
2624 bytesProcessed = numFrames * stream->inputFrameSizeBytes;
2625 stream->readOffset = (stream->readOffset + bytesProcessed) % stream->inputBufferSizeBytes;
2626 IDirectSoundCaptureBuffer_Unlock( stream->pDirectSoundInputBuffer, lpInBuf1, dwInSize1, lpInBuf2, dwInSize2);
2627 }
2628 error2:
2629
2630 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, numFrames );
2631 }
2632
2633 if( stream->callbackResult == paComplete && !PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
2634 {
2635 /* don't return completed until the buffer processor has been drained */
2636 return paContinue;
2637 }
2638 else
2639 {
2640 return stream->callbackResult;
2641 }
2642 }
2643 /*******************************************************************/
2644
2645 static HRESULT ZeroAvailableOutputSpace( PaWinDsStream *stream )
2646 {
2647 HRESULT hr;
2648 LPBYTE lpbuf1 = NULL;
2649 LPBYTE lpbuf2 = NULL;
2650 DWORD dwsize1 = 0;
2651 DWORD dwsize2 = 0;
2652 long bytesEmpty;
2653 hr = QueryOutputSpace( stream, &bytesEmpty );
2654 if (hr != DS_OK) return hr;
2655 if( bytesEmpty == 0 ) return DS_OK;
2656 // Lock free space in the DS
2657 hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, stream->outputBufferWriteOffsetBytes,
2658 bytesEmpty, (void **) &lpbuf1, &dwsize1,
2659 (void **) &lpbuf2, &dwsize2, 0);
2660 if (hr == DS_OK)
2661 {
2662 // Copy the buffer into the DS
2663 ZeroMemory(lpbuf1, dwsize1);
2664 if(lpbuf2 != NULL)
2665 {
2666 ZeroMemory(lpbuf2, dwsize2);
2667 }
2668 // Update our buffer offset and unlock sound buffer
2669 stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + dwsize1 + dwsize2) % stream->outputBufferSizeBytes;
2670 IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2);
2671
2672 stream->finalZeroBytesWritten += dwsize1 + dwsize2;
2673 }
2674 return hr;
2675 }
2676
2677
2678 static void CALLBACK TimerCallback(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2)
2679 {
2680 PaWinDsStream *stream;
2681 int isFinished = 0;
2682
2683 /* suppress unused variable warnings */
2684 (void) uID;
2685 (void) uMsg;
2686 (void) dw1;
2687 (void) dw2;
2688
2689 stream = (PaWinDsStream *) dwUser;
2690 if( stream == NULL ) return;
2691
2692 if( stream->isActive )
2693 {
2694 if( stream->abortProcessing )
2695 {
2696 isFinished = 1;
2697 }
2698 else if( stream->stopProcessing )
2699 {
2700 if( stream->bufferProcessor.outputChannelCount > 0 )
2701 {
2702 ZeroAvailableOutputSpace( stream );
2703 if( stream->finalZeroBytesWritten >= stream->outputBufferSizeBytes )
2704 {
2705 /* once we've flushed the whole output buffer with zeros we know all data has been played */
2706 isFinished = 1;
2707 }
2708 }
2709 else
2710 {
2711 isFinished = 1;
2712 }
2713 }
2714 else
2715 {
2716 int callbackResult = TimeSlice( stream );
2717 if( callbackResult != paContinue )
2718 {
2719 /* FIXME implement handling of paComplete and paAbort if possible
2720 At the moment this should behave as if paComplete was called and
2721 flush the buffer.
2722 */
2723
2724 stream->stopProcessing = 1;
2725 }
2726 }
2727
2728 if( isFinished )
2729 {
2730 if( stream->streamRepresentation.streamFinishedCallback != 0 )
2731 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
2732
2733 stream->isActive = 0; /* don't set this until the stream really is inactive */
2734 SetEvent( stream->processingCompleted );
2735 }
2736 }
2737 }
2738
2739 #ifndef PA_WIN_DS_USE_WMME_TIMER
2740
2741 #ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
2742
2743 static void CALLBACK WaitableTimerAPCProc(
2744 LPVOID lpArg, // Data value
2745 DWORD dwTimerLowValue, // Timer low value
2746 DWORD dwTimerHighValue ) // Timer high value
2747
2748 {
2749 (void)dwTimerLowValue;
2750 (void)dwTimerHighValue;
2751
2752 TimerCallback( 0, 0, (DWORD_PTR)lpArg, 0, 0 );
2753 }
2754
2755 #endif /* PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT */
2756
2757
2758 PA_THREAD_FUNC ProcessingThreadProc( void *pArg )
2759 {
2760 PaWinDsStream *stream = (PaWinDsStream *)pArg;
2761 LARGE_INTEGER dueTime;
2762 int timerPeriodMs;
2763
2764 timerPeriodMs = (int)(stream->pollingPeriodSeconds * MSECS_PER_SECOND);
2765 if( timerPeriodMs < 1 )
2766 timerPeriodMs = 1;
2767
2768 #ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
2769 assert( stream->waitableTimer != NULL );
2770
2771 /* invoke first timeout immediately */
2772 dueTime.LowPart = timerPeriodMs * 1000 * 10;
2773 dueTime.HighPart = 0;
2774
2775 /* tick using waitable timer */
2776 if( SetWaitableTimer( stream->waitableTimer, &dueTime, timerPeriodMs, WaitableTimerAPCProc, pArg, FALSE ) != 0 )
2777 {
2778 DWORD wfsoResult = 0;
2779 do
2780 {
2781 /* wait for processingCompleted to be signaled or our timer APC to be called */
2782 wfsoResult = WaitForSingleObjectEx( stream->processingCompleted, timerPeriodMs * 10, /* alertable = */ TRUE );
2783
2784 }while( wfsoResult == WAIT_TIMEOUT || wfsoResult == WAIT_IO_COMPLETION );
2785 }
2786
2787 CancelWaitableTimer( stream->waitableTimer );
2788
2789 #else
2790
2791 /* tick using WaitForSingleObject timeout */
2792 while ( WaitForSingleObject( stream->processingCompleted, timerPeriodMs ) == WAIT_TIMEOUT )
2793 {
2794 TimerCallback( 0, 0, (DWORD_PTR)pArg, 0, 0 );
2795 }
2796 #endif /* PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT */
2797
2798 SetEvent( stream->processingThreadCompleted );
2799
2800 return 0;
2801 }
2802
2803 #endif /* !PA_WIN_DS_USE_WMME_TIMER */
2804
2805 /***********************************************************************************
2806 When CloseStream() is called, the multi-api layer ensures that
2807 the stream has already been stopped or aborted.
2808 */
2809 static PaError CloseStream( PaStream* s )
2810 {
2811 PaError result = paNoError;
2812 PaWinDsStream *stream = (PaWinDsStream*)s;
2813
2814 CloseHandle( stream->processingCompleted );
2815
2816 #ifdef PA_WIN_DS_USE_WAITABLE_TIMER_OBJECT
2817 if( stream->waitableTimer != NULL )
2818 CloseHandle( stream->waitableTimer );
2819 #endif
2820
2821 #ifndef PA_WIN_DS_USE_WMME_TIMER
2822 CloseHandle( stream->processingThreadCompleted );
2823 #endif
2824
2825 // Cleanup the sound buffers
2826 if( stream->pDirectSoundOutputBuffer )
2827 {
2828 IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
2829 IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );
2830 stream->pDirectSoundOutputBuffer = NULL;
2831 }
2832
2833 if( stream->pDirectSoundPrimaryBuffer )
2834 {
2835 IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
2836 stream->pDirectSoundPrimaryBuffer = NULL;
2837 }
2838
2839 if( stream->pDirectSoundInputBuffer )
2840 {
2841 IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
2842 IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );
2843 stream->pDirectSoundInputBuffer = NULL;
2844 }
2845
2846 if( stream->pDirectSoundCapture )
2847 {
2848 IDirectSoundCapture_Release( stream->pDirectSoundCapture );
2849 stream->pDirectSoundCapture = NULL;
2850 }
2851
2852 if( stream->pDirectSound )
2853 {
2854 IDirectSound_Release( stream->pDirectSound );
2855 stream->pDirectSound = NULL;
2856 }
2857
2858 #ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
2859 if( stream->pDirectSoundFullDuplex8 )
2860 {
2861 IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );
2862 stream->pDirectSoundFullDuplex8 = NULL;
2863 }
2864 #endif
2865
2866 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
2867 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
2868 PaUtil_FreeMemory( stream );
2869
2870 return result;
2871 }
2872
2873 /***********************************************************************************/
2874 static HRESULT ClearOutputBuffer( PaWinDsStream *stream )
2875 {
2876 PaError result = paNoError;
2877 unsigned char* pDSBuffData;
2878 DWORD dwDataLen;
2879 HRESULT hr;
2880
2881 hr = IDirectSoundBuffer_SetCurrentPosition( stream->pDirectSoundOutputBuffer, 0 );
2882 DBUG(("PaHost_ClearOutputBuffer: IDirectSoundBuffer_SetCurrentPosition returned = 0x%X.\n", hr));
2883 if( hr != DS_OK )
2884 return hr;
2885
2886 // Lock the DS buffer
2887 if ((hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, 0, stream->outputBufferSizeBytes, (LPVOID*)&pDSBuffData,
2888 &dwDataLen, NULL, 0, 0)) != DS_OK )
2889 return hr;
2890
2891 // Zero the DS buffer
2892 ZeroMemory(pDSBuffData, dwDataLen);
2893 // Unlock the DS buffer
2894 if ((hr = IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK)
2895 return hr;
2896
2897 // Let DSound set the starting write position because if we set it to zero, it looks like the
2898 // buffer is full to begin with. This causes a long pause before sound starts when using large buffers.
2899 if ((hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
2900 &stream->previousPlayCursor, &stream->outputBufferWriteOffsetBytes )) != DS_OK)
2901 return hr;
2902
2903 /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */
2904
2905 return DS_OK;
2906 }
2907
2908 static PaError StartStream( PaStream *s )
2909 {
2910 PaError result = paNoError;
2911 PaWinDsStream *stream = (PaWinDsStream*)s;
2912 HRESULT hr;
2913
2914 stream->callbackResult = paContinue;
2915 PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
2916
2917 ResetEvent( stream->processingCompleted );
2918
2919 #ifndef PA_WIN_DS_USE_WMME_TIMER
2920 ResetEvent( stream->processingThreadCompleted );
2921 #endif
2922
2923 if( stream->bufferProcessor.inputChannelCount > 0 )
2924 {
2925 // Start the buffer capture
2926 if( stream->pDirectSoundInputBuffer != NULL ) // FIXME: not sure this check is necessary
2927 {
2928 hr = IDirectSoundCaptureBuffer_Start( stream->pDirectSoundInputBuffer, DSCBSTART_LOOPING );
2929 }
2930
2931 DBUG(("StartStream: DSW_StartInput returned = 0x%X.\n", hr));
2932 if( hr != DS_OK )
2933 {
2934 result = paUnanticipatedHostError;
2935 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
2936 goto error;
2937 }
2938 }
2939
2940 stream->framesWritten = 0;
2941 stream->callbackFlags = 0;
2942
2943 stream->abortProcessing = 0;
2944 stream->stopProcessing = 0;
2945
2946 if( stream->bufferProcessor.outputChannelCount > 0 )
2947 {
2948 QueryPerformanceCounter( &stream->previousPlayTime );
2949 stream->finalZeroBytesWritten = 0;
2950
2951 hr = ClearOutputBuffer( stream );
2952 if( hr != DS_OK )
2953 {
2954 result = paUnanticipatedHostError;
2955 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
2956 goto error;
2957 }
2958
2959 if( stream->streamRepresentation.streamCallback && (stream->streamFlags & paPrimeOutputBuffersUsingStreamCallback) )
2960 {
2961 stream->callbackFlags = paPrimingOutput;
2962
2963 TimeSlice( stream );
2964 /* we ignore the return value from TimeSlice here and start the stream as usual.
2965 The first timer callback will detect if the callback has completed. */
2966
2967 stream->callbackFlags = 0;
2968 }
2969
2970 // Start the buffer playback in a loop.
2971 if( stream->pDirectSoundOutputBuffer != NULL ) // FIXME: not sure this needs to be checked here
2972 {
2973 hr = IDirectSoundBuffer_Play( stream->pDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING );
2974 DBUG(("PaHost_StartOutput: IDirectSoundBuffer_Play returned = 0x%X.\n", hr));
2975 if( hr != DS_OK )
2976 {
2977 result = paUnanticipatedHostError;
2978 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
2979 goto error;
2980 }
2981 stream->outputIsRunning = TRUE;
2982 }
2983 }
2984
2985 if( stream->streamRepresentation.streamCallback )
2986 {
2987 TIMECAPS timecaps;
2988 int timerPeriodMs = (int)(stream->pollingPeriodSeconds * MSECS_PER_SECOND);
2989 if( timerPeriodMs < 1 )
2990 timerPeriodMs = 1;
2991
2992 /* set windows scheduler granularity only as fine as needed, no finer */
2993 /* Although this is not fully documented by MS, it appears that
2994 timeBeginPeriod() affects the scheduling granulatity of all timers
2995 including Waitable Timer Objects. So we always call timeBeginPeriod, whether
2996 we're using an MM timer callback via timeSetEvent or not.
2997 */
2998 assert( stream->systemTimerResolutionPeriodMs == 0 );
2999 if( timeGetDevCaps( &timecaps, sizeof(TIMECAPS) ) == MMSYSERR_NOERROR && timecaps.wPeriodMin > 0 )
3000 {
3001 /* aim for resolution 4 times higher than polling rate */
3002 stream->systemTimerResolutionPeriodMs = (UINT)((stream->pollingPeriodSeconds * MSECS_PER_SECOND) * .25);
3003 if( stream->systemTimerResolutionPeriodMs < timecaps.wPeriodMin )
3004 stream->systemTimerResolutionPeriodMs = timecaps.wPeriodMin;
3005 if( stream->systemTimerResolutionPeriodMs > timecaps.wPeriodMax )
3006 stream->systemTimerResolutionPeriodMs = timecaps.wPeriodMax;
3007
3008 if( timeBeginPeriod( stream->systemTimerResolutionPeriodMs ) != MMSYSERR_NOERROR )
3009 stream->systemTimerResolutionPeriodMs = 0; /* timeBeginPeriod failed, so we don't need to call timeEndPeriod() later */
3010 }
3011
3012
3013 #ifdef PA_WIN_DS_USE_WMME_TIMER
3014 /* Create timer that will wake us up so we can fill the DSound buffer. */
3015 /* We have deprecated timeSetEvent because all MM timer callbacks
3016 are serialised onto a single thread. Which creates problems with multiple
3017 PA streams, or when also using timers for other time critical tasks
3018 */
3019 stream->timerID = timeSetEvent( timerPeriodMs, stream->systemTimerResolutionPeriodMs, (LPTIMECALLBACK) TimerCallback,
3020 (DWORD_PTR) stream, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS );
3021
3022 if( stream->timerID == 0 )
3023 {
3024 stream->isActive = 0;
3025 result = paUnanticipatedHostError;
3026 PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
3027 goto error;
3028 }
3029 #else
3030 /* Create processing thread which calls TimerCallback */
3031
3032 stream->processingThread = CREATE_THREAD( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId );
3033 if( !stream->processingThread )
3034 {
3035 result = paUnanticipatedHostError;
3036 PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
3037 goto error;
3038 }
3039
3040 if( !SetThreadPriority( stream->processingThread, THREAD_PRIORITY_TIME_CRITICAL ) )
3041 {
3042 result = paUnanticipatedHostError;
3043 PA_DS_SET_LAST_DIRECTSOUND_ERROR( GetLastError() );
3044 goto error;
3045 }
3046 #endif
3047 }
3048
3049 stream->isActive = 1;
3050 stream->isStarted = 1;
3051
3052 assert( result == paNoError );
3053 return result;
3054
3055 error:
3056
3057 if( stream->pDirectSoundOutputBuffer != NULL && stream->outputIsRunning )
3058 IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
3059 stream->outputIsRunning = FALSE;
3060
3061 #ifndef PA_WIN_DS_USE_WMME_TIMER
3062 if( stream->processingThread )
3063 {
3064 #ifdef CLOSE_THREAD_HANDLE
3065 CLOSE_THREAD_HANDLE( stream->processingThread ); /* Delete thread. */
3066 #endif
3067 stream->processingThread = NULL;
3068 }
3069 #endif
3070
3071 return result;
3072 }
3073
3074
3075 /***********************************************************************************/
3076 static PaError StopStream( PaStream *s )
3077 {
3078 PaError result = paNoError;
3079 PaWinDsStream *stream = (PaWinDsStream*)s;
3080 HRESULT hr;
3081 int timeoutMsec;
3082
3083 if( stream->streamRepresentation.streamCallback )
3084 {
3085 stream->stopProcessing = 1;
3086
3087 /* Set timeout at 4 times maximum time we might wait. */
3088 timeoutMsec = (int) (4 * MSECS_PER_SECOND * (stream->hostBufferSizeFrames / stream->streamRepresentation.streamInfo.sampleRate));
3089
3090 WaitForSingleObject( stream->processingCompleted, timeoutMsec );
3091 }
3092
3093 #ifdef PA_WIN_DS_USE_WMME_TIMER
3094 if( stream->timerID != 0 )
3095 {
3096 timeKillEvent(stream->timerID); /* Stop callback timer. */
3097 stream->timerID = 0;
3098 }
3099 #else
3100 if( stream->processingThread )
3101 {
3102 if( WaitForSingleObject( stream->processingThreadCompleted, 30*100 ) == WAIT_TIMEOUT )
3103 return paUnanticipatedHostError;
3104
3105 #ifdef CLOSE_THREAD_HANDLE
3106 CloseHandle( stream->processingThread ); /* Delete thread. */
3107 stream->processingThread = NULL;
3108 #endif
3109
3110 }
3111 #endif
3112
3113 if( stream->systemTimerResolutionPeriodMs > 0 ){
3114 timeEndPeriod( stream->systemTimerResolutionPeriodMs );
3115 stream->systemTimerResolutionPeriodMs = 0;
3116 }
3117
3118 if( stream->bufferProcessor.outputChannelCount > 0 )
3119 {
3120 // Stop the buffer playback
3121 if( stream->pDirectSoundOutputBuffer != NULL )
3122 {
3123 stream->outputIsRunning = FALSE;
3124 // FIXME: what happens if IDirectSoundBuffer_Stop returns an error?
3125 hr = IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
3126
3127 if( stream->pDirectSoundPrimaryBuffer )
3128 IDirectSoundBuffer_Stop( stream->pDirectSoundPrimaryBuffer ); /* FIXME we never started the primary buffer so I'm not sure we need to stop it */
3129 }
3130 }
3131
3132 if( stream->bufferProcessor.inputChannelCount > 0 )
3133 {
3134 // Stop the buffer capture
3135 if( stream->pDirectSoundInputBuffer != NULL )
3136 {
3137 // FIXME: what happens if IDirectSoundCaptureBuffer_Stop returns an error?
3138 hr = IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
3139 }
3140 }
3141
3142 stream->isStarted = 0;
3143
3144 return result;
3145 }
3146
3147
3148 /***********************************************************************************/
3149 static PaError AbortStream( PaStream *s )
3150 {
3151 PaWinDsStream *stream = (PaWinDsStream*)s;
3152
3153 stream->abortProcessing = 1;
3154 return StopStream( s );
3155 }
3156
3157
3158 /***********************************************************************************/
3159 static PaError IsStreamStopped( PaStream *s )
3160 {
3161 PaWinDsStream *stream = (PaWinDsStream*)s;
3162
3163 return !stream->isStarted;
3164 }
3165
3166
3167 /***********************************************************************************/
3168 static PaError IsStreamActive( PaStream *s )
3169 {
3170 PaWinDsStream *stream = (PaWinDsStream*)s;
3171
3172 return stream->isActive;
3173 }
3174
3175 /***********************************************************************************/
3176 static PaTime GetStreamTime( PaStream *s )
3177 {
3178 /* suppress unused variable warnings */
3179 (void) s;
3180
3181 return PaUtil_GetTime();
3182 }
3183
3184
3185 /***********************************************************************************/
3186 static double GetStreamCpuLoad( PaStream* s )
3187 {
3188 PaWinDsStream *stream = (PaWinDsStream*)s;
3189
3190 return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
3191 }
3192
3193
3194 /***********************************************************************************
3195 As separate stream interfaces are used for blocking and callback
3196 streams, the following functions can be guaranteed to only be called
3197 for blocking streams.
3198 */
3199
3200 static PaError ReadStream( PaStream* s,
3201 void *buffer,
3202 unsigned long frames )
3203 {
3204 PaWinDsStream *stream = (PaWinDsStream*)s;
3205
3206 /* suppress unused variable warnings */
3207 (void) buffer;
3208 (void) frames;
3209 (void) stream;
3210
3211 /* IMPLEMENT ME, see portaudio.h for required behavior*/
3212
3213 return paNoError;
3214 }
3215
3216
3217 /***********************************************************************************/
3218 static PaError WriteStream( PaStream* s,
3219 const void *buffer,
3220 unsigned long frames )
3221 {
3222 PaWinDsStream *stream = (PaWinDsStream*)s;
3223
3224 /* suppress unused variable warnings */
3225 (void) buffer;
3226 (void) frames;
3227 (void) stream;
3228
3229 /* IMPLEMENT ME, see portaudio.h for required behavior*/
3230
3231 return paNoError;
3232 }
3233
3234
3235 /***********************************************************************************/
3236 static signed long GetStreamReadAvailable( PaStream* s )
3237 {
3238 PaWinDsStream *stream = (PaWinDsStream*)s;
3239
3240 /* suppress unused variable warnings */
3241 (void) stream;
3242
3243 /* IMPLEMENT ME, see portaudio.h for required behavior*/
3244
3245 return 0;
3246 }
3247
3248
3249 /***********************************************************************************/
3250 static signed long GetStreamWriteAvailable( PaStream* s )
3251 {
3252 PaWinDsStream *stream = (PaWinDsStream*)s;
3253
3254 /* suppress unused variable warnings */
3255 (void) stream;
3256
3257 /* IMPLEMENT ME, see portaudio.h for required behavior*/
3258
3259 return 0;
3260 }
3261
3262 #endif