Debian Codegraph @

3rdparty/iaxclient/lib/portaudio/src/hostapi/dsound/pa_win_ds.c

raw symbols SCIP
1 /*
2 * $Id: pa_win_ds.c,v 1.1 2006/06/10 21:30:56 dmazzoni Exp $
3 * Portable Audio I/O Library DirectSound implementation
4 *
5 * Authors: Phil Burk, Robert Marsanyi & Ross Bencina
6 * Based on the Open Source API proposed by Ross Bencina
7 * Copyright (c) 1999-2006 Ross Bencina, Phil Burk, Robert Marsanyi
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining
10 * a copy of this software and associated documentation files
11 * (the "Software"), to deal in the Software without restriction,
12 * including without limitation the rights to use, copy, modify, merge,
13 * publish, distribute, sublicense, and/or sell copies of the Software,
14 * and to permit persons to whom the Software is furnished to do so,
15 * subject to the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
19 *
20 * Any person wishing to distribute modifications to the Software is
21 * requested to send the modifications to the original developer so that
22 * they can be incorporated into the canonical version.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
28 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 */
32
33 /** @file
34
35 @todo implement paInputOverflow callback status flag
36
37 @todo implement paNeverDropInput.
38
39 @todo implement host api specific extension to set i/o buffer sizes in frames
40
41 @todo implement initialisation of PaDeviceInfo default*Latency fields (currently set to 0.)
42
43 @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable
44
45 @todo audit handling of DirectSound result codes - in many cases we could convert a HRESULT into
46 a native portaudio error code. Standard DirectSound result codes are documented at msdn.
47
48 @todo implement IsFormatSupported
49
50 @todo check that CoInitialize() CoUninitialize() are always correctly
51 paired, even in error cases.
52
53 @todo call PaUtil_SetLastHostErrorInfo with a specific error string (currently just "DSound error").
54
55 @todo make sure all buffers have been played before stopping the stream
56 when the stream callback returns paComplete
57
58 old TODOs from phil, need to work out if these have been done:
59 O- fix "patest_stop.c"
60 */
61
62 #include <stdio.h>
63 #include <string.h> /* strlen() */
64
65 #include "pa_util.h"
66 #include "pa_allocation.h"
67 #include "pa_hostapi.h"
68 #include "pa_stream.h"
69 #include "pa_cpuload.h"
70 #include "pa_process.h"
71
72 #include "pa_win_ds_dynlink.h"
73
74 #if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
75 #pragma comment( lib, "dsound.lib" )
76 #pragma comment( lib, "winmm.lib" )
77 #endif
78
79 /*
80 provided in newer platform sdks and x64
81 */
82 #ifndef DWORD_PTR
83 #define DWORD_PTR DWORD
84 #endif
85
86 #define PRINT(x) PA_DEBUG(x);
87 #define ERR_RPT(x) PRINT(x)
88 #define DBUG(x) PRINT(x)
89 #define DBUGX(x) PRINT(x)
90
91 #define PA_USE_HIGH_LATENCY (0)
92 #if PA_USE_HIGH_LATENCY
93 #define PA_WIN_9X_LATENCY (500)
94 #define PA_WIN_NT_LATENCY (600)
95 #else
96 #define PA_WIN_9X_LATENCY (140)
97 #define PA_WIN_NT_LATENCY (280)
98 #endif
99
100 #define PA_WIN_WDM_LATENCY (120)
101
102 #define SECONDS_PER_MSEC (0.001)
103 #define MSEC_PER_SECOND (1000)
104
105 /* prototypes for functions declared in this file */
106
107 #ifdef __cplusplus
108 extern "C"
109 {
110 #endif /* __cplusplus */
111
112 PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
113
114 #ifdef __cplusplus
115 }
116 #endif /* __cplusplus */
117
118 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
119 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
120 PaStream** s,
121 const PaStreamParameters *inputParameters,
122 const PaStreamParameters *outputParameters,
123 double sampleRate,
124 unsigned long framesPerBuffer,
125 PaStreamFlags streamFlags,
126 PaStreamCallback *streamCallback,
127 void *userData );
128 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
129 const PaStreamParameters *inputParameters,
130 const PaStreamParameters *outputParameters,
131 double sampleRate );
132 static PaError CloseStream( PaStream* stream );
133 static PaError StartStream( PaStream *stream );
134 static PaError StopStream( PaStream *stream );
135 static PaError AbortStream( PaStream *stream );
136 static PaError IsStreamStopped( PaStream *s );
137 static PaError IsStreamActive( PaStream *stream );
138 static PaTime GetStreamTime( PaStream *stream );
139 static double GetStreamCpuLoad( PaStream* stream );
140 static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
141 static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
142 static signed long GetStreamReadAvailable( PaStream* stream );
143 static signed long GetStreamWriteAvailable( PaStream* stream );
144
145
146 /* FIXME: should convert hr to a string */
147 #define PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ) \
148 PaUtil_SetLastHostErrorInfo( paDirectSound, hr, "DirectSound error" )
149
150 /************************************************* DX Prototypes **********/
151 static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID,
152 LPCTSTR lpszDesc,
153 LPCTSTR lpszDrvName,
154 LPVOID lpContext );
155
156 /************************************************************************************/
157 /********************** Structures **************************************************/
158 /************************************************************************************/
159 /* PaWinDsHostApiRepresentation - host api datastructure specific to this implementation */
160
161 typedef struct PaWinDsDeviceInfo
162 {
163 GUID guid;
164 GUID *lpGUID;
165 double sampleRates[3];
166 } PaWinDsDeviceInfo;
167
168 typedef struct
169 {
170 PaUtilHostApiRepresentation inheritedHostApiRep;
171 PaUtilStreamInterface callbackStreamInterface;
172 PaUtilStreamInterface blockingStreamInterface;
173
174 PaUtilAllocationGroup *allocations;
175
176 /* implementation specific data goes here */
177 PaWinDsDeviceInfo *winDsDeviceInfos;
178
179 } PaWinDsHostApiRepresentation;
180
181
182 /* PaWinDsStream - a stream data structure specifically for this implementation */
183
184 typedef struct PaWinDsStream
185 {
186 PaUtilStreamRepresentation streamRepresentation;
187 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
188 PaUtilBufferProcessor bufferProcessor;
189
190 /* DirectSound specific data. */
191
192 /* Output */
193 LPDIRECTSOUND pDirectSound;
194 LPDIRECTSOUNDBUFFER pDirectSoundOutputBuffer;
195 DWORD outputBufferWriteOffsetBytes; /* last write position */
196 INT outputBufferSizeBytes;
197 INT bytesPerOutputFrame;
198 /* Try to detect play buffer underflows. */
199 LARGE_INTEGER perfCounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */
200 LARGE_INTEGER previousPlayTime;
201 UINT previousPlayCursor;
202 UINT outputUnderflowCount;
203 BOOL outputIsRunning;
204 /* use double which lets us can play for several thousand years with enough precision */
205 double dsw_framesWritten;
206 double framesPlayed;
207 /* Input */
208 LPDIRECTSOUNDCAPTURE pDirectSoundCapture;
209 LPDIRECTSOUNDCAPTUREBUFFER pDirectSoundInputBuffer;
210 INT bytesPerInputFrame;
211 UINT readOffset; /* last read position */
212 UINT inputSize;
213
214
215 MMRESULT timerID;
216 int framesPerDSBuffer;
217 double framesWritten;
218 double secondsPerHostByte; /* Used to optimize latency calculation for outTime */
219
220 PaStreamCallbackFlags callbackFlags;
221
222 /* FIXME - move all below to PaUtilStreamRepresentation */
223 volatile int isStarted;
224 volatile int isActive;
225 volatile int stopProcessing; /* stop thread once existing buffers have been returned */
226 volatile int abortProcessing; /* stop thread immediately */
227 } PaWinDsStream;
228
229
230 /************************************************************************************
231 ** Duplicate the input string using the allocations allocator.
232 ** A NULL string is converted to a zero length string.
233 ** If memory cannot be allocated, NULL is returned.
234 **/
235 static char *DuplicateDeviceNameString( PaUtilAllocationGroup *allocations, const char* src )
236 {
237 char *result = 0;
238
239 if( src != NULL )
240 {
241 size_t len = strlen(src);
242 result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) );
243 if( result )
244 memcpy( (void *) result, src, len+1 );
245 }
246 else
247 {
248 result = (char*)PaUtil_GroupAllocateMemory( allocations, 1 );
249 if( result )
250 result[0] = '\0';
251 }
252
253 return result;
254 }
255
256 /************************************************************************************
257 ** DSDeviceNameAndGUID, DSDeviceNameAndGUIDVector used for collecting preliminary
258 ** information during device enumeration.
259 */
260 typedef struct DSDeviceNameAndGUID{
261 char *name; // allocated from parent's allocations, never deleted by this structure
262 GUID guid;
263 LPGUID lpGUID;
264 } DSDeviceNameAndGUID;
265
266 typedef struct DSDeviceNameAndGUIDVector{
267 PaUtilAllocationGroup *allocations;
268 PaError enumerationError;
269
270 int count;
271 int free;
272 DSDeviceNameAndGUID *items; // Allocated using LocalAlloc()
273 } DSDeviceNameAndGUIDVector;
274
275 static PaError InitializeDSDeviceNameAndGUIDVector(
276 DSDeviceNameAndGUIDVector *guidVector, PaUtilAllocationGroup *allocations )
277 {
278 PaError result = paNoError;
279
280 guidVector->allocations = allocations;
281 guidVector->enumerationError = paNoError;
282
283 guidVector->count = 0;
284 guidVector->free = 8;
285 guidVector->items = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * guidVector->free );
286 if( guidVector->items == NULL )
287 result = paInsufficientMemory;
288
289 return result;
290 }
291
292 static PaError ExpandDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
293 {
294 PaError result = paNoError;
295 DSDeviceNameAndGUID *newItems;
296 int i;
297
298 /* double size of vector */
299 int size = guidVector->count + guidVector->free;
300 guidVector->free += size;
301
302 newItems = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * size * 2 );
303 if( newItems == NULL )
304 {
305 result = paInsufficientMemory;
306 }
307 else
308 {
309 for( i=0; i < guidVector->count; ++i )
310 {
311 newItems[i].name = guidVector->items[i].name;
312 if( guidVector->items[i].lpGUID == NULL )
313 {
314 newItems[i].lpGUID = NULL;
315 }
316 else
317 {
318 newItems[i].lpGUID = &newItems[i].guid;
319 memcpy( &newItems[i].guid, guidVector->items[i].lpGUID, sizeof(GUID) );;
320 }
321 }
322
323 LocalFree( guidVector->items );
324 guidVector->items = newItems;
325 }
326
327 return result;
328 }
329
330 /*
331 it's safe to call DSDeviceNameAndGUIDVector multiple times
332 */
333 static PaError TerminateDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
334 {
335 PaError result = paNoError;
336
337 if( guidVector->items != NULL )
338 {
339 if( LocalFree( guidVector->items ) != NULL )
340 result = paInsufficientMemory; /** @todo this isn't the correct error to return from a deallocation failure */
341
342 guidVector->items = NULL;
343 }
344
345 return result;
346 }
347
348 /************************************************************************************
349 ** Collect preliminary device information during DirectSound enumeration
350 */
351 static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID,
352 LPCTSTR lpszDesc,
353 LPCTSTR lpszDrvName,
354 LPVOID lpContext )
355 {
356 DSDeviceNameAndGUIDVector *namesAndGUIDs = (DSDeviceNameAndGUIDVector*)lpContext;
357 PaError error;
358
359 (void) lpszDrvName; /* unused variable */
360
361 if( namesAndGUIDs->free == 0 )
362 {
363 error = ExpandDSDeviceNameAndGUIDVector( namesAndGUIDs );
364 if( error != paNoError )
365 {
366 namesAndGUIDs->enumerationError = error;
367 return FALSE;
368 }
369 }
370
371 /* Set GUID pointer, copy GUID to storage in DSDeviceNameAndGUIDVector. */
372 if( lpGUID == NULL )
373 {
374 namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = NULL;
375 }
376 else
377 {
378 namesAndGUIDs->items[namesAndGUIDs->count].lpGUID =
379 &namesAndGUIDs->items[namesAndGUIDs->count].guid;
380
381 memcpy( &namesAndGUIDs->items[namesAndGUIDs->count].guid, lpGUID, sizeof(GUID) );
382 }
383
384 namesAndGUIDs->items[namesAndGUIDs->count].name =
385 DuplicateDeviceNameString( namesAndGUIDs->allocations, lpszDesc );
386 if( namesAndGUIDs->items[namesAndGUIDs->count].name == NULL )
387 {
388 namesAndGUIDs->enumerationError = paInsufficientMemory;
389 return FALSE;
390 }
391
392 ++namesAndGUIDs->count;
393 --namesAndGUIDs->free;
394
395 return TRUE;
396 }
397
398
399 /*
400 GUIDs for emulated devices which we blacklist below.
401 are there more than two of them??
402 */
403
404 GUID IID_IRolandVSCEmulated1 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x01};
405 GUID IID_IRolandVSCEmulated2 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x02};
406
407
408 #define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ (13) /* must match array length below */
409 static double defaultSampleRateSearchOrder_[] =
410 { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
411 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
412
413
414 /************************************************************************************
415 ** Extract capabilities from an output device, and add it to the device info list
416 ** if successful. This function assumes that there is enough room in the
417 ** device info list to accomodate all entries.
418 **
419 ** The device will not be added to the device list if any errors are encountered.
420 */
421 static PaError AddOutputDeviceInfoFromDirectSound(
422 PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID )
423 {
424 PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep;
425 PaDeviceInfo *deviceInfo = hostApi->deviceInfos[hostApi->info.deviceCount];
426 PaWinDsDeviceInfo *winDsDeviceInfo = &winDsHostApi->winDsDeviceInfos[hostApi->info.deviceCount];
427 HRESULT hr;
428 LPDIRECTSOUND lpDirectSound;
429 DSCAPS caps;
430 int deviceOK = TRUE;
431 PaError result = paNoError;
432 int i;
433
434 /* Copy GUID to the device info structure. Set pointer. */
435 if( lpGUID == NULL )
436 {
437 winDsDeviceInfo->lpGUID = NULL;
438 }
439 else
440 {
441 memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
442 winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
443 }
444
445
446 if( lpGUID )
447 {
448 if (IsEqualGUID (&IID_IRolandVSCEmulated1,lpGUID) ||
449 IsEqualGUID (&IID_IRolandVSCEmulated2,lpGUID) )
450 {
451 PA_DEBUG(("BLACKLISTED: %s \n",name));
452 return paNoError;
453 }
454 }
455
456 /* Create a DirectSound object for the specified GUID
457 Note that using CoCreateInstance doesn't work on windows CE.
458 */
459 hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &lpDirectSound, NULL );
460
461 /** try using CoCreateInstance because DirectSoundCreate was hanging under
462 some circumstances - note this was probably related to the
463 #define BOOL short bug which has now been fixed
464 @todo delete this comment and the following code once we've ensured
465 there is no bug.
466 */
467 /*
468 hr = CoCreateInstance( &CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER,
469 &IID_IDirectSound, (void**)&lpDirectSound );
470
471 if( hr == S_OK )
472 {
473 hr = IDirectSound_Initialize( lpDirectSound, lpGUID );
474 }
475 */
476
477 if( hr != DS_OK )
478 {
479 if (hr == DSERR_ALLOCATED)
480 PA_DEBUG(("AddOutputDeviceInfoFromDirectSound %s DSERR_ALLOCATED\n",name));
481 DBUG(("Cannot create DirectSound for %s. Result = 0x%x\n", name, hr ));
482 if (lpGUID)
483 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",
484 name,
485 lpGUID->Data1,
486 lpGUID->Data2,
487 lpGUID->Data3,
488 lpGUID->Data4[0],
489 lpGUID->Data4[1],
490 lpGUID->Data4[2],
491 lpGUID->Data4[3],
492 lpGUID->Data4[4],
493 lpGUID->Data4[5],
494 lpGUID->Data4[6],
495 lpGUID->Data4[7]));
496
497 deviceOK = FALSE;
498 }
499 else
500 {
501 /* Query device characteristics. */
502 memset( &caps, 0, sizeof(caps) );
503 caps.dwSize = sizeof(caps);
504 hr = IDirectSound_GetCaps( lpDirectSound, &caps );
505 if( hr != DS_OK )
506 {
507 DBUG(("Cannot GetCaps() for DirectSound device %s. Result = 0x%x\n", name, hr ));
508 deviceOK = FALSE;
509 }
510 else
511 {
512
513 #ifndef PA_NO_WMME
514 if( caps.dwFlags & DSCAPS_EMULDRIVER )
515 {
516 /* If WMME supported, then reject Emulated drivers because they are lousy. */
517 deviceOK = FALSE;
518 }
519 #endif
520
521 if( deviceOK )
522 {
523 deviceInfo->maxInputChannels = 0;
524 /* Mono or stereo device? */
525 deviceInfo->maxOutputChannels = ( caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
526
527 deviceInfo->defaultLowInputLatency = 0.; /** @todo IMPLEMENT ME */
528 deviceInfo->defaultLowOutputLatency = 0.; /** @todo IMPLEMENT ME */
529 deviceInfo->defaultHighInputLatency = 0.; /** @todo IMPLEMENT ME */
530 deviceInfo->defaultHighOutputLatency = 0.; /** @todo IMPLEMENT ME */
531
532 /* initialize defaultSampleRate */
533
534 if( caps.dwFlags & DSCAPS_CONTINUOUSRATE )
535 {
536 /* initialize to caps.dwMaxSecondarySampleRate incase none of the standard rates match */
537 deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
538
539 for( i = 0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
540 {
541 if( defaultSampleRateSearchOrder_[i] >= caps.dwMinSecondarySampleRate
542 && defaultSampleRateSearchOrder_[i] <= caps.dwMaxSecondarySampleRate ){
543
544 deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[i];
545 break;
546 }
547 }
548 }
549 else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate )
550 {
551 if( caps.dwMinSecondarySampleRate == 0 )
552 {
553 /*
554 ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !!
555 ** But it supports continuous sampling.
556 ** So fake range of rates, and hope it really supports it.
557 */
558 deviceInfo->defaultSampleRate = 44100.0f;
559
560 DBUG(("PA - Reported rates both zero. Setting to fake values for device #%s\n", name ));
561 }
562 else
563 {
564 deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
565 }
566 }
567 else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) )
568 {
569 /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000.
570 ** But we know that they really support a range of rates!
571 ** So when we see a ridiculous set of rates, assume it is a range.
572 */
573 deviceInfo->defaultSampleRate = 44100.0f;
574 DBUG(("PA - Sample rate range used instead of two odd values for device #%s\n", name ));
575 }
576 else deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
577
578
579 //printf( "min %d max %d\n", caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate );
580 // dwFlags | DSCAPS_CONTINUOUSRATE
581 }
582 }
583
584 IDirectSound_Release( lpDirectSound );
585 }
586
587 if( deviceOK )
588 {
589 deviceInfo->name = name;
590
591 if( lpGUID == NULL )
592 hostApi->info.defaultOutputDevice = hostApi->info.deviceCount;
593
594 hostApi->info.deviceCount++;
595 }
596
597 return result;
598 }
599
600
601 /************************************************************************************
602 ** Extract capabilities from an input device, and add it to the device info list
603 ** if successful. This function assumes that there is enough room in the
604 ** device info list to accomodate all entries.
605 **
606 ** The device will not be added to the device list if any errors are encountered.
607 */
608 static PaError AddInputDeviceInfoFromDirectSoundCapture(
609 PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID )
610 {
611 PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep;
612 PaDeviceInfo *deviceInfo = hostApi->deviceInfos[hostApi->info.deviceCount];
613 PaWinDsDeviceInfo *winDsDeviceInfo = &winDsHostApi->winDsDeviceInfos[hostApi->info.deviceCount];
614 HRESULT hr;
615 LPDIRECTSOUNDCAPTURE lpDirectSoundCapture;
616 DSCCAPS caps;
617 int deviceOK = TRUE;
618 PaError result = paNoError;
619
620 /* Copy GUID to the device info structure. Set pointer. */
621 if( lpGUID == NULL )
622 {
623 winDsDeviceInfo->lpGUID = NULL;
624 }
625 else
626 {
627 winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
628 memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
629 }
630
631
632 hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL );
633
634 /** try using CoCreateInstance because DirectSoundCreate was hanging under
635 some circumstances - note this was probably related to the
636 #define BOOL short bug which has now been fixed
637 @todo delete this comment and the following code once we've ensured
638 there is no bug.
639 */
640 /*
641 hr = CoCreateInstance( &CLSID_DirectSoundCapture, NULL, CLSCTX_INPROC_SERVER,
642 &IID_IDirectSoundCapture, (void**)&lpDirectSoundCapture );
643 */
644 if( hr != DS_OK )
645 {
646 DBUG(("Cannot create Capture for %s. Result = 0x%x\n", name, hr ));
647 deviceOK = FALSE;
648 }
649 else
650 {
651 /* Query device characteristics. */
652 memset( &caps, 0, sizeof(caps) );
653 caps.dwSize = sizeof(caps);
654 hr = IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps );
655 if( hr != DS_OK )
656 {
657 DBUG(("Cannot GetCaps() for Capture device %s. Result = 0x%x\n", name, hr ));
658 deviceOK = FALSE;
659 }
660 else
661 {
662 #ifndef PA_NO_WMME
663 if( caps.dwFlags & DSCAPS_EMULDRIVER )
664 {
665 /* If WMME supported, then reject Emulated drivers because they are lousy. */
666 deviceOK = FALSE;
667 }
668 #endif
669
670 if( deviceOK )
671 {
672 deviceInfo->maxInputChannels = caps.dwChannels;
673 deviceInfo->maxOutputChannels = 0;
674
675 deviceInfo->defaultLowInputLatency = 0.; /** @todo IMPLEMENT ME */
676 deviceInfo->defaultLowOutputLatency = 0.; /** @todo IMPLEMENT ME */
677 deviceInfo->defaultHighInputLatency = 0.; /** @todo IMPLEMENT ME */
678 deviceInfo->defaultHighOutputLatency = 0.; /** @todo IMPLEMENT ME */
679
680 /* constants from a WINE patch by Francois Gouget, see:
681 http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
682
683 ---
684 Date: Fri, 14 May 2004 10:38:12 +0200 (CEST)
685 From: Francois Gouget <fgouget@ ... .fr>
686 To: Ross Bencina <rbencina@ ... .au>
687 Subject: Re: Permission to use wine 48/96 wave patch in BSD licensed library
688
689 [snip]
690
691 I give you permission to use the patch below under the BSD license.
692 http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
693
694 [snip]
695 */
696 #ifndef WAVE_FORMAT_48M08
697 #define WAVE_FORMAT_48M08 0x00001000 /* 48 kHz, Mono, 8-bit */
698 #define WAVE_FORMAT_48S08 0x00002000 /* 48 kHz, Stereo, 8-bit */
699 #define WAVE_FORMAT_48M16 0x00004000 /* 48 kHz, Mono, 16-bit */
700 #define WAVE_FORMAT_48S16 0x00008000 /* 48 kHz, Stereo, 16-bit */
701 #define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */
702 #define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */
703 #define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */
704 #define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */
705 #endif
706
707 /* defaultSampleRate */
708 if( caps.dwChannels == 2 )
709 {
710 if( caps.dwFormats & WAVE_FORMAT_4S16 )
711 deviceInfo->defaultSampleRate = 44100.0;
712 else if( caps.dwFormats & WAVE_FORMAT_48S16 )
713 deviceInfo->defaultSampleRate = 48000.0;
714 else if( caps.dwFormats & WAVE_FORMAT_2S16 )
715 deviceInfo->defaultSampleRate = 22050.0;
716 else if( caps.dwFormats & WAVE_FORMAT_1S16 )
717 deviceInfo->defaultSampleRate = 11025.0;
718 else if( caps.dwFormats & WAVE_FORMAT_96S16 )
719 deviceInfo->defaultSampleRate = 96000.0;
720 else
721 deviceInfo->defaultSampleRate = 0.;
722 }
723 else if( caps.dwChannels == 1 )
724 {
725 if( caps.dwFormats & WAVE_FORMAT_4M16 )
726 deviceInfo->defaultSampleRate = 44100.0;
727 else if( caps.dwFormats & WAVE_FORMAT_48M16 )
728 deviceInfo->defaultSampleRate = 48000.0;
729 else if( caps.dwFormats & WAVE_FORMAT_2M16 )
730 deviceInfo->defaultSampleRate = 22050.0;
731 else if( caps.dwFormats & WAVE_FORMAT_1M16 )
732 deviceInfo->defaultSampleRate = 11025.0;
733 else if( caps.dwFormats & WAVE_FORMAT_96M16 )
734 deviceInfo->defaultSampleRate = 96000.0;
735 else
736 deviceInfo->defaultSampleRate = 0.;
737 }
738 else deviceInfo->defaultSampleRate = 0.;
739 }
740 }
741
742 IDirectSoundCapture_Release( lpDirectSoundCapture );
743 }
744
745 if( deviceOK )
746 {
747 deviceInfo->name = name;
748
749 if( lpGUID == NULL )
750 hostApi->info.defaultInputDevice = hostApi->info.deviceCount;
751
752 hostApi->info.deviceCount++;
753 }
754
755 return result;
756 }
757
758
759 /***********************************************************************************/
760 PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
761 {
762 PaError result = paNoError;
763 int i, deviceCount;
764 PaWinDsHostApiRepresentation *winDsHostApi;
765 DSDeviceNameAndGUIDVector inputNamesAndGUIDs, outputNamesAndGUIDs;
766 PaDeviceInfo *deviceInfoArray;
767
768 HRESULT hr = CoInitialize(NULL); /** @todo: should uninitialize too */
769 if( FAILED(hr) ){
770 return paUnanticipatedHostError;
771 }
772
773 /* initialise guid vectors so they can be safely deleted on error */
774 inputNamesAndGUIDs.items = NULL;
775 outputNamesAndGUIDs.items = NULL;
776
777 PaWinDs_InitializeDSoundEntryPoints();
778
779 winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) );
780 if( !winDsHostApi )
781 {
782 result = paInsufficientMemory;
783 goto error;
784 }
785
786 winDsHostApi->allocations = PaUtil_CreateAllocationGroup();
787 if( !winDsHostApi->allocations )
788 {
789 result = paInsufficientMemory;
790 goto error;
791 }
792
793 *hostApi = &winDsHostApi->inheritedHostApiRep;
794 (*hostApi)->info.structVersion = 1;
795 (*hostApi)->info.type = paDirectSound;
796 (*hostApi)->info.name = "Windows DirectSound";
797
798 (*hostApi)->info.deviceCount = 0;
799 (*hostApi)->info.defaultInputDevice = paNoDevice;
800 (*hostApi)->info.defaultOutputDevice = paNoDevice;
801
802
803 /* DSound - enumerate devices to count them and to gather their GUIDs */
804
805
806 result = InitializeDSDeviceNameAndGUIDVector( &inputNamesAndGUIDs, winDsHostApi->allocations );
807 if( result != paNoError )
808 goto error;
809
810 result = InitializeDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs, winDsHostApi->allocations );
811 if( result != paNoError )
812 goto error;
813
814 paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&inputNamesAndGUIDs );
815
816 paWinDsDSoundEntryPoints.DirectSoundEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&outputNamesAndGUIDs );
817
818 if( inputNamesAndGUIDs.enumerationError != paNoError )
819 {
820 result = inputNamesAndGUIDs.enumerationError;
821 goto error;
822 }
823
824 if( outputNamesAndGUIDs.enumerationError != paNoError )
825 {
826 result = outputNamesAndGUIDs.enumerationError;
827 goto error;
828 }
829
830 deviceCount = inputNamesAndGUIDs.count + outputNamesAndGUIDs.count;
831
832 if( deviceCount > 0 )
833 {
834 /* allocate array for pointers to PaDeviceInfo structs */
835 (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
836 winDsHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );
837 if( !(*hostApi)->deviceInfos )
838 {
839 result = paInsufficientMemory;
840 goto error;
841 }
842
843 /* allocate all PaDeviceInfo structs in a contiguous block */
844 deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(
845 winDsHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount );
846 if( !deviceInfoArray )
847 {
848 result = paInsufficientMemory;
849 goto error;
850 }
851
852 /* allocate all DSound specific info structs in a contiguous block */
853 winDsHostApi->winDsDeviceInfos = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory(
854 winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount );
855 if( !winDsHostApi->winDsDeviceInfos )
856 {
857 result = paInsufficientMemory;
858 goto error;
859 }
860
861 for( i=0; i < deviceCount; ++i )
862 {
863 PaDeviceInfo *deviceInfo = &deviceInfoArray[i];
864 deviceInfo->structVersion = 2;
865 deviceInfo->hostApi = hostApiIndex;
866 deviceInfo->name = 0;
867 (*hostApi)->deviceInfos[i] = deviceInfo;
868 }
869
870 for( i=0; i< inputNamesAndGUIDs.count; ++i )
871 {
872 result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi,
873 inputNamesAndGUIDs.items[i].name,
874 inputNamesAndGUIDs.items[i].lpGUID );
875 if( result != paNoError )
876 goto error;
877 }
878
879 for( i=0; i< outputNamesAndGUIDs.count; ++i )
880 {
881 result = AddOutputDeviceInfoFromDirectSound( winDsHostApi,
882 outputNamesAndGUIDs.items[i].name,
883 outputNamesAndGUIDs.items[i].lpGUID );
884 if( result != paNoError )
885 goto error;
886 }
887 }
888
889 result = TerminateDSDeviceNameAndGUIDVector( &inputNamesAndGUIDs );
890 if( result != paNoError )
891 goto error;
892
893 result = TerminateDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs );
894 if( result != paNoError )
895 goto error;
896
897
898 (*hostApi)->Terminate = Terminate;
899 (*hostApi)->OpenStream = OpenStream;
900 (*hostApi)->IsFormatSupported = IsFormatSupported;
901
902 PaUtil_InitializeStreamInterface( &winDsHostApi->callbackStreamInterface, CloseStream, StartStream,
903 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
904 GetStreamTime, GetStreamCpuLoad,
905 PaUtil_DummyRead, PaUtil_DummyWrite,
906 PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
907
908 PaUtil_InitializeStreamInterface( &winDsHostApi->blockingStreamInterface, CloseStream, StartStream,
909 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
910 GetStreamTime, PaUtil_DummyGetCpuLoad,
911 ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
912
913 return result;
914
915 error:
916 if( winDsHostApi )
917 {
918 if( winDsHostApi->allocations )
919 {
920 PaUtil_FreeAllAllocations( winDsHostApi->allocations );
921 PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );
922 }
923
924 PaUtil_FreeMemory( winDsHostApi );
925 }
926
927 TerminateDSDeviceNameAndGUIDVector( &inputNamesAndGUIDs );
928 TerminateDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs );
929
930 return result;
931 }
932
933
934 /***********************************************************************************/
935 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
936 {
937 PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
938
939 /*
940 IMPLEMENT ME:
941 - clean up any resources not handled by the allocation group
942 */
943
944 if( winDsHostApi->allocations )
945 {
946 PaUtil_FreeAllAllocations( winDsHostApi->allocations );
947 PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );
948 }
949
950 PaUtil_FreeMemory( winDsHostApi );
951
952 PaWinDs_TerminateDSoundEntryPoints();
953
954 CoUninitialize();
955 }
956
957
958 /* Set minimal latency based on whether NT or Win95.
959 * NT has higher latency.
960 */
961 static int PaWinDS_GetMinSystemLatency( void )
962 {
963 int minLatencyMsec;
964 /* Set minimal latency based on whether NT or other OS.
965 * NT has higher latency.
966 */
967 OSVERSIONINFO osvi;
968 osvi.dwOSVersionInfoSize = sizeof( osvi );
969 GetVersionEx( &osvi );
970 DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId ));
971 DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion ));
972 DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion ));
973 /* Check for NT */
974 if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
975 {
976 minLatencyMsec = PA_WIN_NT_LATENCY;
977 }
978 else if(osvi.dwMajorVersion >= 5)
979 {
980 minLatencyMsec = PA_WIN_WDM_LATENCY;
981 }
982 else
983 {
984 minLatencyMsec = PA_WIN_9X_LATENCY;
985 }
986 return minLatencyMsec;
987 }
988
989 /***********************************************************************************/
990 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
991 const PaStreamParameters *inputParameters,
992 const PaStreamParameters *outputParameters,
993 double sampleRate )
994 {
995 int inputChannelCount, outputChannelCount;
996 PaSampleFormat inputSampleFormat, outputSampleFormat;
997
998 if( inputParameters )
999 {
1000 inputChannelCount = inputParameters->channelCount;
1001 inputSampleFormat = inputParameters->sampleFormat;
1002
1003 /* unless alternate device specification is supported, reject the use of
1004 paUseHostApiSpecificDeviceSpecification */
1005
1006 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
1007 return paInvalidDevice;
1008
1009 /* check that input device can support inputChannelCount */
1010 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
1011 return paInvalidChannelCount;
1012
1013 /* validate inputStreamInfo */
1014 if( inputParameters->hostApiSpecificStreamInfo )
1015 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
1016 }
1017 else
1018 {
1019 inputChannelCount = 0;
1020 }
1021
1022 if( outputParameters )
1023 {
1024 outputChannelCount = outputParameters->channelCount;
1025 outputSampleFormat = outputParameters->sampleFormat;
1026
1027 /* unless alternate device specification is supported, reject the use of
1028 paUseHostApiSpecificDeviceSpecification */
1029
1030 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
1031 return paInvalidDevice;
1032
1033 /* check that output device can support inputChannelCount */
1034 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
1035 return paInvalidChannelCount;
1036
1037 /* validate outputStreamInfo */
1038 if( outputParameters->hostApiSpecificStreamInfo )
1039 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
1040 }
1041 else
1042 {
1043 outputChannelCount = 0;
1044 }
1045
1046 /*
1047 IMPLEMENT ME:
1048
1049 - if a full duplex stream is requested, check that the combination
1050 of input and output parameters is supported if necessary
1051
1052 - check that the device supports sampleRate
1053
1054 Because the buffer adapter handles conversion between all standard
1055 sample formats, the following checks are only required if paCustomFormat
1056 is implemented, or under some other unusual conditions.
1057
1058 - check that input device can support inputSampleFormat, or that
1059 we have the capability to convert from outputSampleFormat to
1060 a native format
1061
1062 - check that output device can support outputSampleFormat, or that
1063 we have the capability to convert from outputSampleFormat to
1064 a native format
1065 */
1066
1067 return paFormatIsSupported;
1068 }
1069
1070
1071 /*************************************************************************
1072 ** Determine minimum number of buffers required for this host based
1073 ** on minimum latency. Latency can be optionally set by user by setting
1074 ** an environment variable. For example, to set latency to 200 msec, put:
1075 **
1076 ** set PA_MIN_LATENCY_MSEC=200
1077 **
1078 ** in the AUTOEXEC.BAT file and reboot.
1079 ** If the environment variable is not set, then the latency will be determined
1080 ** based on the OS. Windows NT has higher latency than Win95.
1081 */
1082 #define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC")
1083 #define PA_ENV_BUF_SIZE (32)
1084
1085 static int PaWinDs_GetMinLatencyFrames( double sampleRate )
1086 {
1087 char envbuf[PA_ENV_BUF_SIZE];
1088 DWORD hresult;
1089 int minLatencyMsec = 0;
1090
1091 /* Let user determine minimal latency by setting environment variable. */
1092 hresult = GetEnvironmentVariable( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE );
1093 if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) )
1094 {
1095 minLatencyMsec = atoi( envbuf );
1096 }
1097 else
1098 {
1099 minLatencyMsec = PaWinDS_GetMinSystemLatency();
1100 #if PA_USE_HIGH_LATENCY
1101 PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec ));
1102 #endif
1103
1104 }
1105
1106 return (int) (minLatencyMsec * sampleRate * SECONDS_PER_MSEC);
1107 }
1108
1109
1110 static HRESULT InitInputBuffer( PaWinDsStream *stream, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer )
1111 {
1112 DSCBUFFERDESC captureDesc;
1113 WAVEFORMATEX wfFormat;
1114 HRESULT result;
1115
1116 stream->bytesPerInputFrame = nChannels * sizeof(short);
1117
1118 // Define the buffer format
1119 wfFormat.wFormatTag = WAVE_FORMAT_PCM;
1120 wfFormat.nChannels = nChannels;
1121 wfFormat.nSamplesPerSec = nFrameRate;
1122 wfFormat.wBitsPerSample = 8 * sizeof(short);
1123 wfFormat.nBlockAlign = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
1124 wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
1125 wfFormat.cbSize = 0; /* No extended format info. */
1126 stream->inputSize = bytesPerBuffer;
1127 // ----------------------------------------------------------------------
1128 // Setup the secondary buffer description
1129 ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));
1130 captureDesc.dwSize = sizeof(DSCBUFFERDESC);
1131 captureDesc.dwFlags = 0;
1132 captureDesc.dwBufferBytes = bytesPerBuffer;
1133 captureDesc.lpwfxFormat = &wfFormat;
1134 // Create the capture buffer
1135 if ((result = IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,
1136 &captureDesc, &stream->pDirectSoundInputBuffer, NULL)) != DS_OK) return result;
1137 stream->readOffset = 0; // reset last read position to start of buffer
1138 return DS_OK;
1139 }
1140
1141
1142 static HRESULT InitOutputBuffer( PaWinDsStream *stream, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer )
1143 {
1144 DWORD dwDataLen;
1145 DWORD playCursor;
1146 HRESULT result;
1147 LPDIRECTSOUNDBUFFER pPrimaryBuffer;
1148 HWND hWnd;
1149 HRESULT hr;
1150 WAVEFORMATEX wfFormat;
1151 DSBUFFERDESC primaryDesc;
1152 DSBUFFERDESC secondaryDesc;
1153 unsigned char* pDSBuffData;
1154 LARGE_INTEGER counterFrequency;
1155
1156 stream->outputBufferSizeBytes = bytesPerBuffer;
1157 stream->outputIsRunning = FALSE;
1158 stream->outputUnderflowCount = 0;
1159 stream->dsw_framesWritten = 0;
1160 stream->bytesPerOutputFrame = nChannels * sizeof(short);
1161
1162 // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the
1163 // applications's window. Also if that window is closed before the Buffer is closed
1164 // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.)
1165 // So we will use GetDesktopWindow() which was suggested by Miller Puckette.
1166 // hWnd = GetForegroundWindow();
1167 //
1168 // FIXME: The example code I have on the net creates a hidden window that
1169 // is managed by our code - I think we should do that - one hidden
1170 // window for the whole of Pa_DS
1171 //
1172 hWnd = GetDesktopWindow();
1173
1174 // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz.
1175 // Exclusize also prevents unexpected sounds from other apps during a performance.
1176 if ((hr = IDirectSound_SetCooperativeLevel( stream->pDirectSound,
1177 hWnd, DSSCL_EXCLUSIVE)) != DS_OK)
1178 {
1179 return hr;
1180 }
1181
1182 // -----------------------------------------------------------------------
1183 // Create primary buffer and set format just so we can specify our custom format.
1184 // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz.
1185 // Setup the primary buffer description
1186 ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC));
1187 primaryDesc.dwSize = sizeof(DSBUFFERDESC);
1188 primaryDesc.dwFlags = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth
1189 primaryDesc.dwBufferBytes = 0;
1190 primaryDesc.lpwfxFormat = NULL;
1191 // Create the buffer
1192 if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
1193 &primaryDesc, &pPrimaryBuffer, NULL)) != DS_OK) return result;
1194 // Define the buffer format
1195 wfFormat.wFormatTag = WAVE_FORMAT_PCM;
1196 wfFormat.nChannels = nChannels;
1197 wfFormat.nSamplesPerSec = nFrameRate;
1198 wfFormat.wBitsPerSample = 8 * sizeof(short);
1199 wfFormat.nBlockAlign = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
1200 wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
1201 wfFormat.cbSize = 0; /* No extended format info. */
1202 // Set the primary buffer's format
1203 if((result = IDirectSoundBuffer_SetFormat( pPrimaryBuffer, &wfFormat)) != DS_OK) return result;
1204
1205 // ----------------------------------------------------------------------
1206 // Setup the secondary buffer description
1207 ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC));
1208 secondaryDesc.dwSize = sizeof(DSBUFFERDESC);
1209 secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
1210 secondaryDesc.dwBufferBytes = bytesPerBuffer;
1211 secondaryDesc.lpwfxFormat = &wfFormat;
1212 // Create the secondary buffer
1213 if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
1214 &secondaryDesc, &stream->pDirectSoundOutputBuffer, NULL)) != DS_OK) return result;
1215 // Lock the DS buffer
1216 if ((result = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, 0, stream->outputBufferSizeBytes, (LPVOID*)&pDSBuffData,
1217 &dwDataLen, NULL, 0, 0)) != DS_OK) return result;
1218 // Zero the DS buffer
1219 ZeroMemory(pDSBuffData, dwDataLen);
1220 // Unlock the DS buffer
1221 if ((result = IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK) return result;
1222 if( QueryPerformanceFrequency( &counterFrequency ) )
1223 {
1224 int framesInBuffer = bytesPerBuffer / (nChannels * sizeof(short));
1225 stream->perfCounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * framesInBuffer) / nFrameRate;
1226 }
1227 else
1228 {
1229 stream->perfCounterTicksPerBuffer.QuadPart = 0;
1230 }
1231 // Let DSound set the starting write position because if we set it to zero, it looks like the
1232 // buffer is full to begin with. This causes a long pause before sound starts when using large buffers.
1233 hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
1234 &playCursor, &stream->outputBufferWriteOffsetBytes );
1235 if( hr != DS_OK )
1236 {
1237 return hr;
1238 }
1239 stream->dsw_framesWritten = stream->outputBufferWriteOffsetBytes / stream->bytesPerOutputFrame;
1240 /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */
1241 return DS_OK;
1242 }
1243
1244
1245 /***********************************************************************************/
1246 /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
1247
1248 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
1249 PaStream** s,
1250 const PaStreamParameters *inputParameters,
1251 const PaStreamParameters *outputParameters,
1252 double sampleRate,
1253 unsigned long framesPerBuffer,
1254 PaStreamFlags streamFlags,
1255 PaStreamCallback *streamCallback,
1256 void *userData )
1257 {
1258 PaError result = paNoError;
1259 PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
1260 PaWinDsStream *stream = 0;
1261 int inputChannelCount, outputChannelCount;
1262 PaSampleFormat inputSampleFormat, outputSampleFormat;
1263 PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
1264 unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames;
1265
1266 if( inputParameters )
1267 {
1268 inputChannelCount = inputParameters->channelCount;
1269 inputSampleFormat = inputParameters->sampleFormat;
1270 suggestedInputLatencyFrames = (unsigned long)(inputParameters->suggestedLatency * sampleRate);
1271
1272 /* IDEA: the following 3 checks could be performed by default by pa_front
1273 unless some flag indicated otherwise */
1274
1275 /* unless alternate device specification is supported, reject the use of
1276 paUseHostApiSpecificDeviceSpecification */
1277 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
1278 return paInvalidDevice;
1279
1280 /* check that input device can support inputChannelCount */
1281 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
1282 return paInvalidChannelCount;
1283
1284 /* validate hostApiSpecificStreamInfo */
1285 if( inputParameters->hostApiSpecificStreamInfo )
1286 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
1287 }
1288 else
1289 {
1290 inputChannelCount = 0;
1291 suggestedInputLatencyFrames = 0;
1292 }
1293
1294
1295 if( outputParameters )
1296 {
1297 outputChannelCount = outputParameters->channelCount;
1298 outputSampleFormat = outputParameters->sampleFormat;
1299 suggestedOutputLatencyFrames = (unsigned long)(outputParameters->suggestedLatency * sampleRate);
1300
1301 /* unless alternate device specification is supported, reject the use of
1302 paUseHostApiSpecificDeviceSpecification */
1303 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
1304 return paInvalidDevice;
1305
1306 /* check that output device can support inputChannelCount */
1307 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
1308 return paInvalidChannelCount;
1309
1310 /* validate hostApiSpecificStreamInfo */
1311 if( outputParameters->hostApiSpecificStreamInfo )
1312 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
1313 }
1314 else
1315 {
1316 outputChannelCount = 0;
1317 suggestedOutputLatencyFrames = 0;
1318 }
1319
1320
1321 /*
1322 IMPLEMENT ME:
1323
1324 ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() )
1325
1326 - check that input device can support inputSampleFormat, or that
1327 we have the capability to convert from outputSampleFormat to
1328 a native format
1329
1330 - check that output device can support outputSampleFormat, or that
1331 we have the capability to convert from outputSampleFormat to
1332 a native format
1333
1334 - if a full duplex stream is requested, check that the combination
1335 of input and output parameters is supported
1336
1337 - check that the device supports sampleRate
1338
1339 - alter sampleRate to a close allowable rate if possible / necessary
1340
1341 - validate suggestedInputLatency and suggestedOutputLatency parameters,
1342 use default values where necessary
1343 */
1344
1345
1346 /* validate platform specific flags */
1347 if( (streamFlags & paPlatformSpecificFlags) != 0 )
1348 return paInvalidFlag; /* unexpected platform specific flag */
1349
1350
1351 stream = (PaWinDsStream*)PaUtil_AllocateMemory( sizeof(PaWinDsStream) );
1352 if( !stream )
1353 {
1354 result = paInsufficientMemory;
1355 goto error;
1356 }
1357
1358 memset( stream, 0, sizeof(PaWinDsStream) ); /* initialize all stream variables to 0 */
1359
1360 if( streamCallback )
1361 {
1362 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
1363 &winDsHostApi->callbackStreamInterface, streamCallback, userData );
1364 }
1365 else
1366 {
1367 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
1368 &winDsHostApi->blockingStreamInterface, streamCallback, userData );
1369 }
1370
1371 PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
1372
1373
1374 if( inputParameters )
1375 {
1376 /* IMPLEMENT ME - establish which host formats are available */
1377 hostInputSampleFormat =
1378 PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputParameters->sampleFormat );
1379 }
1380
1381 if( outputParameters )
1382 {
1383 /* IMPLEMENT ME - establish which host formats are available */
1384 hostOutputSampleFormat =
1385 PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputParameters->sampleFormat );
1386 }
1387
1388 result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
1389 inputChannelCount, inputSampleFormat, hostInputSampleFormat,
1390 outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
1391 sampleRate, streamFlags, framesPerBuffer,
1392 framesPerBuffer, /* ignored in paUtilVariableHostBufferSizePartialUsageAllowed mode. */
1393 /* This next mode is required because DS can split the host buffer when it wraps around. */
1394 paUtilVariableHostBufferSizePartialUsageAllowed,
1395 streamCallback, userData );
1396 if( result != paNoError )
1397 goto error;
1398
1399
1400 stream->streamRepresentation.streamInfo.inputLatency =
1401 PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor); /* FIXME: not initialised anywhere else */
1402 stream->streamRepresentation.streamInfo.outputLatency =
1403 PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor); /* FIXME: not initialised anywhere else */
1404 stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
1405
1406
1407 /* DirectSound specific initialization */
1408 {
1409 HRESULT hr;
1410 int bytesPerDirectSoundBuffer;
1411 int userLatencyFrames;
1412 int minLatencyFrames;
1413
1414 stream->timerID = 0;
1415
1416 /* Get system minimum latency. */
1417 minLatencyFrames = PaWinDs_GetMinLatencyFrames( sampleRate );
1418
1419 /* Let user override latency by passing latency parameter. */
1420 userLatencyFrames = (suggestedInputLatencyFrames > suggestedOutputLatencyFrames)
1421 ? suggestedInputLatencyFrames
1422 : suggestedOutputLatencyFrames;
1423 if( userLatencyFrames > 0 ) minLatencyFrames = userLatencyFrames;
1424
1425 /* Calculate stream->framesPerDSBuffer depending on framesPerBuffer */
1426 if( framesPerBuffer == paFramesPerBufferUnspecified )
1427 {
1428 /* App support variable framesPerBuffer */
1429 stream->framesPerDSBuffer = minLatencyFrames;
1430
1431 stream->streamRepresentation.streamInfo.outputLatency = (double)(minLatencyFrames - 1) / sampleRate;
1432 }
1433 else
1434 {
1435 /* Round up to number of buffers needed to guarantee that latency. */
1436 int numUserBuffers = (minLatencyFrames + framesPerBuffer - 1) / framesPerBuffer;
1437 if( numUserBuffers < 1 ) numUserBuffers = 1;
1438 numUserBuffers += 1; /* So we have latency worth of buffers ahead of current buffer. */
1439 stream->framesPerDSBuffer = framesPerBuffer * numUserBuffers;
1440
1441 stream->streamRepresentation.streamInfo.outputLatency = (double)(framesPerBuffer * (numUserBuffers-1)) / sampleRate;
1442 }
1443
1444 {
1445 /** @todo REVIEW: this calculation seems incorrect to me - rossb. */
1446 int msecLatency = (int) ((stream->framesPerDSBuffer * MSEC_PER_SECOND) / sampleRate);
1447 PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", stream->framesPerDSBuffer, msecLatency ));
1448 }
1449
1450
1451 /* ------------------ OUTPUT */
1452 if( outputParameters )
1453 {
1454 /*
1455 PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ outputParameters->device ];
1456 DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", outputParameters->device));
1457 */
1458
1459 bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * outputParameters->channelCount * sizeof(short);
1460 if( bytesPerDirectSoundBuffer < DSBSIZE_MIN )
1461 {
1462 result = paBufferTooSmall;
1463 goto error;
1464 }
1465 else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX )
1466 {
1467 result = paBufferTooBig;
1468 goto error;
1469 }
1470
1471
1472 hr = paWinDsDSoundEntryPoints.DirectSoundCreate( winDsHostApi->winDsDeviceInfos[outputParameters->device].lpGUID,
1473 &stream->pDirectSound, NULL );
1474 if( hr != DS_OK )
1475 {
1476 ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));
1477 result = paUnanticipatedHostError;
1478 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
1479 goto error;
1480 }
1481 hr = InitOutputBuffer( stream,
1482 (unsigned long) (sampleRate + 0.5),
1483 (WORD)outputParameters->channelCount, bytesPerDirectSoundBuffer );
1484 DBUG(("InitOutputBuffer() returns %x\n", hr));
1485 if( hr != DS_OK )
1486 {
1487 result = paUnanticipatedHostError;
1488 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
1489 goto error;
1490 }
1491 /* Calculate value used in latency calculation to avoid real-time divides. */
1492 stream->secondsPerHostByte = 1.0 /
1493 (stream->bufferProcessor.bytesPerHostOutputSample *
1494 outputChannelCount * sampleRate);
1495 }
1496
1497 /* ------------------ INPUT */
1498 if( inputParameters )
1499 {
1500 /*
1501 PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ inputParameters->device ];
1502 DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", inputParameters->device));
1503 */
1504
1505 bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * inputParameters->channelCount * sizeof(short);
1506 if( bytesPerDirectSoundBuffer < DSBSIZE_MIN )
1507 {
1508 result = paBufferTooSmall;
1509 goto error;
1510 }
1511 else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX )
1512 {
1513 result = paBufferTooBig;
1514 goto error;
1515 }
1516
1517 hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( winDsHostApi->winDsDeviceInfos[inputParameters->device].lpGUID,
1518 &stream->pDirectSoundCapture, NULL );
1519 if( hr != DS_OK )
1520 {
1521 ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));
1522 result = paUnanticipatedHostError;
1523 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
1524 goto error;
1525 }
1526 hr = InitInputBuffer( stream,
1527 (unsigned long) (sampleRate + 0.5),
1528 (WORD)inputParameters->channelCount, bytesPerDirectSoundBuffer );
1529 DBUG(("InitInputBuffer() returns %x\n", hr));
1530 if( hr != DS_OK )
1531 {
1532 ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));
1533 result = paUnanticipatedHostError;
1534 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
1535 goto error;
1536 }
1537 }
1538
1539 }
1540
1541 *s = (PaStream*)stream;
1542
1543 return result;
1544
1545 error:
1546 if( stream )
1547 PaUtil_FreeMemory( stream );
1548
1549 return result;
1550 }
1551
1552
1553 /************************************************************************************
1554 * Determine how much space can be safely written to in DS buffer.
1555 * Detect underflows and overflows.
1556 * Does not allow writing into safety gap maintained by DirectSound.
1557 */
1558 static HRESULT QueryOutputSpace( PaWinDsStream *stream, long *bytesEmpty )
1559 {
1560 HRESULT hr;
1561 DWORD playCursor;
1562 DWORD writeCursor;
1563 long numBytesEmpty;
1564 long playWriteGap;
1565 // Query to see how much room is in buffer.
1566 hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
1567 &playCursor, &writeCursor );
1568 if( hr != DS_OK )
1569 {
1570 return hr;
1571 }
1572 // Determine size of gap between playIndex and WriteIndex that we cannot write into.
1573 playWriteGap = writeCursor - playCursor;
1574 if( playWriteGap < 0 ) playWriteGap += stream->outputBufferSizeBytes; // unwrap
1575 /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */
1576 /* Attempt to detect playCursor wrap-around and correct it. */
1577 if( stream->outputIsRunning && (stream->perfCounterTicksPerBuffer.QuadPart != 0) )
1578 {
1579 /* How much time has elapsed since last check. */
1580 LARGE_INTEGER currentTime;
1581 LARGE_INTEGER elapsedTime;
1582 long bytesPlayed;
1583 long bytesExpected;
1584 long buffersWrapped;
1585 QueryPerformanceCounter( &currentTime );
1586 elapsedTime.QuadPart = currentTime.QuadPart - stream->previousPlayTime.QuadPart;
1587 stream->previousPlayTime = currentTime;
1588 /* How many bytes does DirectSound say have been played. */
1589 bytesPlayed = playCursor - stream->previousPlayCursor;
1590 if( bytesPlayed < 0 ) bytesPlayed += stream->outputBufferSizeBytes; // unwrap
1591 stream->previousPlayCursor = playCursor;
1592 /* Calculate how many bytes we would have expected to been played by now. */
1593 bytesExpected = (long) ((elapsedTime.QuadPart * stream->outputBufferSizeBytes) / stream->perfCounterTicksPerBuffer.QuadPart);
1594 buffersWrapped = (bytesExpected - bytesPlayed) / stream->outputBufferSizeBytes;
1595 if( buffersWrapped > 0 )
1596 {
1597 playCursor += (buffersWrapped * stream->outputBufferSizeBytes);
1598 bytesPlayed += (buffersWrapped * stream->outputBufferSizeBytes);
1599 }
1600 /* Maintain frame output cursor. */
1601 stream->framesPlayed += (bytesPlayed / stream->bytesPerOutputFrame);
1602 }
1603 numBytesEmpty = playCursor - stream->outputBufferWriteOffsetBytes;
1604 if( numBytesEmpty < 0 ) numBytesEmpty += stream->outputBufferSizeBytes; // unwrap offset
1605 /* Have we underflowed? */
1606 if( numBytesEmpty > (stream->outputBufferSizeBytes - playWriteGap) )
1607 {
1608 if( stream->outputIsRunning )
1609 {
1610 stream->outputUnderflowCount += 1;
1611 }
1612 stream->outputBufferWriteOffsetBytes = writeCursor;
1613 numBytesEmpty = stream->outputBufferSizeBytes - playWriteGap;
1614 }
1615 *bytesEmpty = numBytesEmpty;
1616 return hr;
1617 }
1618
1619 /***********************************************************************************/
1620 static PaError Pa_TimeSlice( PaWinDsStream *stream )
1621 {
1622 PaError result = 0; /* FIXME: this should be declared int and this function should also return that type (same as stream callback return type)*/
1623 long numFrames = 0;
1624 long bytesEmpty = 0;
1625 long bytesFilled = 0;
1626 long bytesToXfer = 0;
1627 long framesToXfer = 0;
1628 long numInFramesReady = 0;
1629 long numOutFramesReady = 0;
1630 long bytesProcessed;
1631 HRESULT hresult;
1632 double outputLatency = 0;
1633 PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */
1634
1635 /* Input */
1636 LPBYTE lpInBuf1 = NULL;
1637 LPBYTE lpInBuf2 = NULL;
1638 DWORD dwInSize1 = 0;
1639 DWORD dwInSize2 = 0;
1640 /* Output */
1641 LPBYTE lpOutBuf1 = NULL;
1642 LPBYTE lpOutBuf2 = NULL;
1643 DWORD dwOutSize1 = 0;
1644 DWORD dwOutSize2 = 0;
1645
1646 /* How much input data is available? */
1647 if( stream->bufferProcessor.inputChannelCount > 0 )
1648 {
1649 HRESULT hr;
1650 DWORD capturePos;
1651 DWORD readPos;
1652 long filled = 0;
1653 // Query to see how much data is in buffer.
1654 // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly
1655 // so let's pass a pointer just to be safe.
1656 hr = IDirectSoundCaptureBuffer_GetCurrentPosition( stream->pDirectSoundInputBuffer, &capturePos, &readPos );
1657 if( hr == DS_OK )
1658 {
1659 filled = readPos - stream->readOffset;
1660 if( filled < 0 ) filled += stream->inputSize; // unwrap offset
1661 bytesFilled = filled;
1662 }
1663 // FIXME: what happens if IDirectSoundCaptureBuffer_GetCurrentPosition fails?
1664
1665 framesToXfer = numInFramesReady = bytesFilled / stream->bytesPerInputFrame;
1666 outputLatency = ((double)bytesFilled) * stream->secondsPerHostByte;
1667
1668 /** @todo Check for overflow */
1669 }
1670
1671 /* How much output room is available? */
1672 if( stream->bufferProcessor.outputChannelCount > 0 )
1673 {
1674 UINT previousUnderflowCount = stream->outputUnderflowCount;
1675 QueryOutputSpace( stream, &bytesEmpty );
1676 framesToXfer = numOutFramesReady = bytesEmpty / stream->bytesPerOutputFrame;
1677
1678 /* Check for underflow */
1679 if( stream->outputUnderflowCount != previousUnderflowCount )
1680 stream->callbackFlags |= paOutputUnderflow;
1681 }
1682
1683 if( (numInFramesReady > 0) && (numOutFramesReady > 0) )
1684 {
1685 framesToXfer = (numOutFramesReady < numInFramesReady) ? numOutFramesReady : numInFramesReady;
1686 }
1687
1688 if( framesToXfer > 0 )
1689 {
1690
1691 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
1692
1693 /* The outputBufferDacTime parameter should indicates the time at which
1694 the first sample of the output buffer is heard at the DACs. */
1695 timeInfo.currentTime = PaUtil_GetTime();
1696 timeInfo.outputBufferDacTime = timeInfo.currentTime + outputLatency;
1697
1698
1699 PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, stream->callbackFlags );
1700 stream->callbackFlags = 0;
1701
1702 /* Input */
1703 if( stream->bufferProcessor.inputChannelCount > 0 )
1704 {
1705 bytesToXfer = framesToXfer * stream->bytesPerInputFrame;
1706 hresult = IDirectSoundCaptureBuffer_Lock ( stream->pDirectSoundInputBuffer,
1707 stream->readOffset, bytesToXfer,
1708 (void **) &lpInBuf1, &dwInSize1,
1709 (void **) &lpInBuf2, &dwInSize2, 0);
1710 if (hresult != DS_OK)
1711 {
1712 ERR_RPT(("DirectSound IDirectSoundCaptureBuffer_Lock failed, hresult = 0x%x\n",hresult));
1713 result = paUnanticipatedHostError;
1714 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult );
1715 goto error2;
1716 }
1717
1718 numFrames = dwInSize1 / stream->bytesPerInputFrame;
1719 PaUtil_SetInputFrameCount( &stream->bufferProcessor, numFrames );
1720 PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf1, 0 );
1721 /* Is input split into two regions. */
1722 if( dwInSize2 > 0 )
1723 {
1724 numFrames = dwInSize2 / stream->bytesPerInputFrame;
1725 PaUtil_Set2ndInputFrameCount( &stream->bufferProcessor, numFrames );
1726 PaUtil_Set2ndInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf2, 0 );
1727 }
1728 }
1729
1730 /* Output */
1731 if( stream->bufferProcessor.outputChannelCount > 0 )
1732 {
1733 bytesToXfer = framesToXfer * stream->bytesPerOutputFrame;
1734 hresult = IDirectSoundBuffer_Lock ( stream->pDirectSoundOutputBuffer,
1735 stream->outputBufferWriteOffsetBytes, bytesToXfer,
1736 (void **) &lpOutBuf1, &dwOutSize1,
1737 (void **) &lpOutBuf2, &dwOutSize2, 0);
1738 if (hresult != DS_OK)
1739 {
1740 ERR_RPT(("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n",hresult));
1741 result = paUnanticipatedHostError;
1742 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult );
1743 goto error1;
1744 }
1745
1746 numFrames = dwOutSize1 / stream->bytesPerOutputFrame;
1747 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, numFrames );
1748 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf1, 0 );
1749
1750 /* Is output split into two regions. */
1751 if( dwOutSize2 > 0 )
1752 {
1753 numFrames = dwOutSize2 / stream->bytesPerOutputFrame;
1754 PaUtil_Set2ndOutputFrameCount( &stream->bufferProcessor, numFrames );
1755 PaUtil_Set2ndInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf2, 0 );
1756 }
1757 }
1758
1759 result = paContinue;
1760 numFrames = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &result );
1761 stream->framesWritten += numFrames;
1762
1763 if( stream->bufferProcessor.outputChannelCount > 0 )
1764 {
1765 /* FIXME: an underflow could happen here */
1766
1767 /* Update our buffer offset and unlock sound buffer */
1768 bytesProcessed = numFrames * stream->bytesPerOutputFrame;
1769 stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + bytesProcessed) % stream->outputBufferSizeBytes;
1770 IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2);
1771 stream->dsw_framesWritten += numFrames;
1772 }
1773
1774 error1:
1775 if( stream->bufferProcessor.inputChannelCount > 0 )
1776 {
1777 /* FIXME: an overflow could happen here */
1778
1779 /* Update our buffer offset and unlock sound buffer */
1780 bytesProcessed = numFrames * stream->bytesPerInputFrame;
1781 stream->readOffset = (stream->readOffset + bytesProcessed) % stream->inputSize;
1782 IDirectSoundCaptureBuffer_Unlock( stream->pDirectSoundInputBuffer, lpInBuf1, dwInSize1, lpInBuf2, dwInSize2);
1783 }
1784 error2:
1785
1786 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, numFrames );
1787
1788 }
1789
1790 return result;
1791 }
1792 /*******************************************************************/
1793
1794 static HRESULT ZeroAvailableOutputSpace( PaWinDsStream *stream )
1795 {
1796 HRESULT hr;
1797 LPBYTE lpbuf1 = NULL;
1798 LPBYTE lpbuf2 = NULL;
1799 DWORD dwsize1 = 0;
1800 DWORD dwsize2 = 0;
1801 long bytesEmpty;
1802 hr = QueryOutputSpace( stream, &bytesEmpty ); // updates framesPlayed
1803 if (hr != DS_OK) return hr;
1804 if( bytesEmpty == 0 ) return DS_OK;
1805 // Lock free space in the DS
1806 hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, stream->outputBufferWriteOffsetBytes,
1807 bytesEmpty, (void **) &lpbuf1, &dwsize1,
1808 (void **) &lpbuf2, &dwsize2, 0);
1809 if (hr == DS_OK)
1810 {
1811 // Copy the buffer into the DS
1812 ZeroMemory(lpbuf1, dwsize1);
1813 if(lpbuf2 != NULL)
1814 {
1815 ZeroMemory(lpbuf2, dwsize2);
1816 }
1817 // Update our buffer offset and unlock sound buffer
1818 stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + dwsize1 + dwsize2) % stream->outputBufferSizeBytes;
1819 IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2);
1820 stream->dsw_framesWritten += bytesEmpty / stream->bytesPerOutputFrame;
1821 }
1822 return hr;
1823 }
1824
1825
1826 static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2)
1827 {
1828 PaWinDsStream *stream;
1829
1830 /* suppress unused variable warnings */
1831 (void) uID;
1832 (void) uMsg;
1833 (void) dw1;
1834 (void) dw2;
1835
1836 stream = (PaWinDsStream *) dwUser;
1837 if( stream == NULL ) return;
1838
1839 if( stream->isActive )
1840 {
1841 if( stream->abortProcessing )
1842 {
1843 stream->isActive = 0;
1844 }
1845 else if( stream->stopProcessing )
1846 {
1847 if( stream->bufferProcessor.outputChannelCount > 0 )
1848 {
1849 ZeroAvailableOutputSpace( stream );
1850 /* clear isActive when all sound played */
1851 if( stream->framesPlayed >= stream->framesWritten )
1852 {
1853 stream->isActive = 0;
1854 }
1855 }
1856 else
1857 {
1858 stream->isActive = 0;
1859 }
1860 }
1861 else
1862 {
1863 if( Pa_TimeSlice( stream ) != 0) /* Call time slice independant of timing method. */
1864 {
1865 /* FIXME implement handling of paComplete and paAbort if possible */
1866 stream->stopProcessing = 1;
1867 }
1868 }
1869
1870 if( !stream->isActive ){
1871 if( stream->streamRepresentation.streamFinishedCallback != 0 )
1872 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
1873 }
1874 }
1875 }
1876
1877 /***********************************************************************************
1878 When CloseStream() is called, the multi-api layer ensures that
1879 the stream has already been stopped or aborted.
1880 */
1881 static PaError CloseStream( PaStream* s )
1882 {
1883 PaError result = paNoError;
1884 PaWinDsStream *stream = (PaWinDsStream*)s;
1885
1886 // Cleanup the sound buffers
1887 if( stream->pDirectSoundOutputBuffer )
1888 {
1889 IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
1890 IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );
1891 stream->pDirectSoundOutputBuffer = NULL;
1892 }
1893
1894 if( stream->pDirectSoundInputBuffer )
1895 {
1896 IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
1897 IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );
1898 stream->pDirectSoundInputBuffer = NULL;
1899 }
1900
1901 if( stream->pDirectSoundCapture )
1902 {
1903 IDirectSoundCapture_Release( stream->pDirectSoundCapture );
1904 stream->pDirectSoundCapture = NULL;
1905 }
1906
1907 if( stream->pDirectSound )
1908 {
1909 IDirectSound_Release( stream->pDirectSound );
1910 stream->pDirectSound = NULL;
1911 }
1912
1913 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
1914 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
1915 PaUtil_FreeMemory( stream );
1916
1917 return result;
1918 }
1919
1920 /***********************************************************************************/
1921 static PaError StartStream( PaStream *s )
1922 {
1923 PaError result = paNoError;
1924 PaWinDsStream *stream = (PaWinDsStream*)s;
1925 HRESULT hr;
1926
1927 PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
1928
1929 if( stream->bufferProcessor.inputChannelCount > 0 )
1930 {
1931 // Start the buffer playback
1932 if( stream->pDirectSoundInputBuffer != NULL ) // FIXME: not sure this check is necessary
1933 {
1934 hr = IDirectSoundCaptureBuffer_Start( stream->pDirectSoundInputBuffer, DSCBSTART_LOOPING );
1935 }
1936
1937 DBUG(("StartStream: DSW_StartInput returned = 0x%X.\n", hr));
1938 if( hr != DS_OK )
1939 {
1940 result = paUnanticipatedHostError;
1941 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
1942 goto error;
1943 }
1944 }
1945
1946 stream->framesWritten = 0;
1947 stream->callbackFlags = 0;
1948
1949 stream->abortProcessing = 0;
1950 stream->stopProcessing = 0;
1951 stream->isActive = 1;
1952
1953 if( stream->bufferProcessor.outputChannelCount > 0 )
1954 {
1955 /* Give user callback a chance to pre-fill buffer. REVIEW - i thought we weren't pre-filling, rb. */
1956 result = Pa_TimeSlice( stream );
1957 if( result != paNoError ) return result; // FIXME - what if finished?
1958
1959 QueryPerformanceCounter( &stream->previousPlayTime );
1960 stream->previousPlayCursor = 0;
1961 stream->framesPlayed = 0;
1962 hr = IDirectSoundBuffer_SetCurrentPosition( stream->pDirectSoundOutputBuffer, 0 );
1963 DBUG(("PaHost_StartOutput: IDirectSoundBuffer_SetCurrentPosition returned = 0x%X.\n", hr));
1964 if( hr != DS_OK )
1965 {
1966 result = paUnanticipatedHostError;
1967 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
1968 goto error;
1969 }
1970
1971 // Start the buffer playback in a loop.
1972 if( stream->pDirectSoundOutputBuffer != NULL ) // FIXME: not sure this needs to be checked here
1973 {
1974 hr = IDirectSoundBuffer_Play( stream->pDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING );
1975 DBUG(("PaHost_StartOutput: IDirectSoundBuffer_Play returned = 0x%X.\n", hr));
1976 if( hr != DS_OK )
1977 {
1978 result = paUnanticipatedHostError;
1979 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
1980 goto error;
1981 }
1982 stream->outputIsRunning = TRUE;
1983 }
1984 }
1985
1986
1987 /* Create timer that will wake us up so we can fill the DSound buffer. */
1988 {
1989 int resolution;
1990 int framesPerWakeup = stream->framesPerDSBuffer / 4;
1991 int msecPerWakeup = MSEC_PER_SECOND * framesPerWakeup / (int) stream->streamRepresentation.streamInfo.sampleRate;
1992 if( msecPerWakeup < 10 ) msecPerWakeup = 10;
1993 else if( msecPerWakeup > 100 ) msecPerWakeup = 100;
1994 resolution = msecPerWakeup/4;
1995 stream->timerID = timeSetEvent( msecPerWakeup, resolution, (LPTIMECALLBACK) Pa_TimerCallback,
1996 (DWORD_PTR) stream, TIME_PERIODIC );
1997 }
1998 if( stream->timerID == 0 )
1999 {
2000 stream->isActive = 0;
2001 result = paUnanticipatedHostError;
2002 PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
2003 goto error;
2004 }
2005
2006 stream->isStarted = TRUE;
2007
2008 error:
2009 return result;
2010 }
2011
2012
2013 /***********************************************************************************/
2014 static PaError StopStream( PaStream *s )
2015 {
2016 PaError result = paNoError;
2017 PaWinDsStream *stream = (PaWinDsStream*)s;
2018 HRESULT hr;
2019 int timeoutMsec;
2020
2021 stream->stopProcessing = 1;
2022 /* Set timeout at 20% beyond maximum time we might wait. */
2023 timeoutMsec = (int) (1200.0 * stream->framesPerDSBuffer / stream->streamRepresentation.streamInfo.sampleRate);
2024 while( stream->isActive && (timeoutMsec > 0) )
2025 {
2026 Sleep(10);
2027 timeoutMsec -= 10;
2028 }
2029 if( stream->timerID != 0 )
2030 {
2031 timeKillEvent(stream->timerID); /* Stop callback timer. */
2032 stream->timerID = 0;
2033 }
2034
2035
2036 if( stream->bufferProcessor.outputChannelCount > 0 )
2037 {
2038 // Stop the buffer playback
2039 if( stream->pDirectSoundOutputBuffer != NULL )
2040 {
2041 stream->outputIsRunning = FALSE;
2042 // FIXME: what happens if IDirectSoundBuffer_Stop returns an error?
2043 hr = IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
2044 }
2045 }
2046
2047 if( stream->bufferProcessor.inputChannelCount > 0 )
2048 {
2049 // Stop the buffer capture
2050 if( stream->pDirectSoundInputBuffer != NULL )
2051 {
2052 // FIXME: what happens if IDirectSoundCaptureBuffer_Stop returns an error?
2053 hr = IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
2054 }
2055 }
2056
2057 stream->isStarted = FALSE;
2058
2059 return result;
2060 }
2061
2062
2063 /***********************************************************************************/
2064 static PaError AbortStream( PaStream *s )
2065 {
2066 PaWinDsStream *stream = (PaWinDsStream*)s;
2067
2068 stream->abortProcessing = 1;
2069 return StopStream( s );
2070 }
2071
2072
2073 /***********************************************************************************/
2074 static PaError IsStreamStopped( PaStream *s )
2075 {
2076 PaWinDsStream *stream = (PaWinDsStream*)s;
2077
2078 return !stream->isStarted;
2079 }
2080
2081
2082 /***********************************************************************************/
2083 static PaError IsStreamActive( PaStream *s )
2084 {
2085 PaWinDsStream *stream = (PaWinDsStream*)s;
2086
2087 return stream->isActive;
2088 }
2089
2090 /***********************************************************************************/
2091 static PaTime GetStreamTime( PaStream *s )
2092 {
2093 /* suppress unused variable warnings */
2094 (void) s;
2095
2096 return PaUtil_GetTime();
2097 }
2098
2099
2100 /***********************************************************************************/
2101 static double GetStreamCpuLoad( PaStream* s )
2102 {
2103 PaWinDsStream *stream = (PaWinDsStream*)s;
2104
2105 return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
2106 }
2107
2108
2109 /***********************************************************************************
2110 As separate stream interfaces are used for blocking and callback
2111 streams, the following functions can be guaranteed to only be called
2112 for blocking streams.
2113 */
2114
2115 static PaError ReadStream( PaStream* s,
2116 void *buffer,
2117 unsigned long frames )
2118 {
2119 PaWinDsStream *stream = (PaWinDsStream*)s;
2120
2121 /* suppress unused variable warnings */
2122 (void) buffer;
2123 (void) frames;
2124 (void) stream;
2125
2126 /* IMPLEMENT ME, see portaudio.h for required behavior*/
2127
2128 return paNoError;
2129 }
2130
2131
2132 /***********************************************************************************/
2133 static PaError WriteStream( PaStream* s,
2134 const void *buffer,
2135 unsigned long frames )
2136 {
2137 PaWinDsStream *stream = (PaWinDsStream*)s;
2138
2139 /* suppress unused variable warnings */
2140 (void) buffer;
2141 (void) frames;
2142 (void) stream;
2143
2144 /* IMPLEMENT ME, see portaudio.h for required behavior*/
2145
2146 return paNoError;
2147 }
2148
2149
2150 /***********************************************************************************/
2151 static signed long GetStreamReadAvailable( PaStream* s )
2152 {
2153 PaWinDsStream *stream = (PaWinDsStream*)s;
2154
2155 /* suppress unused variable warnings */
2156 (void) stream;
2157
2158 /* IMPLEMENT ME, see portaudio.h for required behavior*/
2159
2160 return 0;
2161 }
2162
2163
2164 /***********************************************************************************/
2165 static signed long GetStreamWriteAvailable( PaStream* s )
2166 {
2167 PaWinDsStream *stream = (PaWinDsStream*)s;
2168
2169 /* suppress unused variable warnings */
2170 (void) stream;
2171
2172 /* IMPLEMENT ME, see portaudio.h for required behavior*/
2173
2174 return 0;
2175 }
2176
2177
2178