Debian Codegraph @

3rdparty/iaxclient/lib/portaudio/src/hostapi/wmme/pa_win_wmme.c

raw symbols SCIP
1 /*
2 * $Id: pa_win_wmme.c,v 1.1 2006/06/10 21:30:56 dmazzoni Exp $
3 * pa_win_wmme.c
4 * Implementation of PortAudio for Windows MultiMedia Extensions (WMME)
5 *
6 * PortAudio Portable Real-Time Audio Library
7 * Latest Version at: http://www.portaudio.com
8 *
9 * Authors: Ross Bencina and Phil Burk
10 * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
11 *
12 * Permission is hereby granted, free of charge, to any person obtaining
13 * a copy of this software and associated documentation files
14 * (the "Software"), to deal in the Software without restriction,
15 * including without limitation the rights to use, copy, modify, merge,
16 * publish, distribute, sublicense, and/or sell copies of the Software,
17 * and to permit persons to whom the Software is furnished to do so,
18 * subject to the following conditions:
19 *
20 * The above copyright notice and this permission notice shall be
21 * included in all copies or substantial portions of the Software.
22 *
23 * Any person wishing to distribute modifications to the Software is
24 * requested to send the modifications to the original developer so that
25 * they can be incorporated into the canonical version.
26 *
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
30 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
31 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
32 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 *
35 */
36
37 /* Modification History:
38 PLB = Phil Burk
39 JM = Julien Maillard
40 RDB = Ross Bencina
41 PLB20010402 - sDevicePtrs now allocates based on sizeof(pointer)
42 PLB20010413 - check for excessive numbers of channels
43 PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC
44 including conditional inclusion of memory.h,
45 and explicit typecasting on memory allocation
46 PLB20010802 - use GlobalAlloc for sDevicesPtr instead of PaHost_AllocFastMemory
47 PLB20010816 - pass process instead of thread to SetPriorityClass()
48 PLB20010927 - use number of frames instead of real-time for CPULoad calculation.
49 JM20020118 - prevent hung thread when buffers underflow.
50 PLB20020321 - detect Win XP versus NT, 9x; fix DBUG typo; removed init of CurrentCount
51 RDB20020411 - various renaming cleanups, factored streamData alloc and cpu usage init
52 RDB20020417 - stopped counting WAVE_MAPPER when there were no real devices
53 refactoring, renaming and fixed a few edge case bugs
54 RDB20020531 - converted to V19 framework
55 ** NOTE maintanance history is now stored in CVS **
56 */
57
58 /** @file
59
60 @todo Fix buffer catch up code, can sometimes get stuck (perhaps fixed now,
61 needs to be reviewed and tested.)
62
63 @todo implement paInputUnderflow, paOutputOverflow streamCallback statusFlags, paNeverDropInput.
64
65 @todo BUG: PA_MME_SET_LAST_WAVEIN/OUT_ERROR is used in functions which may
66 be called asynchronously from the callback thread. this is bad.
67
68 @todo implement inputBufferAdcTime in callback thread
69
70 @todo review/fix error recovery and cleanup in marked functions
71
72 @todo implement timeInfo for stream priming
73
74 @todo handle the case where the callback returns paAbort or paComplete during stream priming.
75
76 @todo review input overflow and output underflow handling in ReadStream and WriteStream
77
78 Non-critical stuff for the future:
79
80 @todo Investigate supporting host buffer formats > 16 bits
81
82 @todo define UNICODE and _UNICODE in the project settings and see what breaks
83
84 */
85
86 /*
87 How it works:
88
89 For both callback and blocking read/write streams we open the MME devices
90 in CALLBACK_EVENT mode. In this mode, MME signals an Event object whenever
91 it has finished with a buffer (either filled it for input, or played it
92 for output). Where necessary we block waiting for Event objects using
93 WaitMultipleObjects().
94
95 When implementing a PA callback stream, we set up a high priority thread
96 which waits on the MME buffer Events and drains/fills the buffers when
97 they are ready.
98
99 When implementing a PA blocking read/write stream, we simply wait on these
100 Events (when necessary) inside the ReadStream() and WriteStream() functions.
101 */
102
103 #include <stdio.h>
104 #include <stdlib.h>
105 #include <math.h>
106 #include <windows.h>
107 #include <mmsystem.h>
108 #include <process.h>
109 #include <assert.h>
110 /* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */
111 #ifndef __MWERKS__
112 #include <malloc.h>
113 #include <memory.h>
114 #endif /* __MWERKS__ */
115
116 #include "portaudio.h"
117 #include "pa_trace.h"
118 #include "pa_util.h"
119 #include "pa_allocation.h"
120 #include "pa_hostapi.h"
121 #include "pa_stream.h"
122 #include "pa_cpuload.h"
123 #include "pa_process.h"
124
125 #include "pa_win_wmme.h"
126
127 #if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
128 #pragma comment(lib, "winmm.lib")
129 #endif
130
131 /*
132 provided in newer platform sdks
133 */
134 #ifndef DWORD_PTR
135 #define DWORD_PTR DWORD
136 #endif
137
138 /************************************************* Constants ********/
139
140 #define PA_MME_USE_HIGH_DEFAULT_LATENCY_ (0) /* For debugging glitches. */
141
142 #if PA_MME_USE_HIGH_DEFAULT_LATENCY_
143 #define PA_MME_WIN_9X_DEFAULT_LATENCY_ (0.4)
144 #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ (4)
145 #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ (4)
146 #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_ (4)
147 #define PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ (16)
148 #define PA_MME_MAX_HOST_BUFFER_SECS_ (0.3) /* Do not exceed unless user buffer exceeds */
149 #define PA_MME_MAX_HOST_BUFFER_BYTES_ (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
150 #else
151 #define PA_MME_WIN_9X_DEFAULT_LATENCY_ (0.2)
152 #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ (2)
153 #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ (3)
154 #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_ (2)
155 #define PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ (16)
156 #define PA_MME_MAX_HOST_BUFFER_SECS_ (0.1) /* Do not exceed unless user buffer exceeds */
157 #define PA_MME_MAX_HOST_BUFFER_BYTES_ (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
158 #endif
159
160 /* Use higher latency for NT because it is even worse at real-time
161 operation than Win9x.
162 */
163 #define PA_MME_WIN_NT_DEFAULT_LATENCY_ (PA_MME_WIN_9X_DEFAULT_LATENCY_ * 2)
164 #define PA_MME_WIN_WDM_DEFAULT_LATENCY_ (PA_MME_WIN_9X_DEFAULT_LATENCY_)
165
166
167 #define PA_MME_MIN_TIMEOUT_MSEC_ (1000)
168
169 static const char constInputMapperSuffix_[] = " - Input";
170 static const char constOutputMapperSuffix_[] = " - Output";
171
172 /********************************************************************/
173
174 typedef struct PaWinMmeStream PaWinMmeStream; /* forward declaration */
175
176 /* prototypes for functions declared in this file */
177
178 #ifdef __cplusplus
179 extern "C"
180 {
181 #endif /* __cplusplus */
182
183 PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
184
185 #ifdef __cplusplus
186 }
187 #endif /* __cplusplus */
188
189 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
190 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
191 PaStream** stream,
192 const PaStreamParameters *inputParameters,
193 const PaStreamParameters *outputParameters,
194 double sampleRate,
195 unsigned long framesPerBuffer,
196 PaStreamFlags streamFlags,
197 PaStreamCallback *streamCallback,
198 void *userData );
199 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
200 const PaStreamParameters *inputParameters,
201 const PaStreamParameters *outputParameters,
202 double sampleRate );
203 static PaError CloseStream( PaStream* stream );
204 static PaError StartStream( PaStream *stream );
205 static PaError StopStream( PaStream *stream );
206 static PaError AbortStream( PaStream *stream );
207 static PaError IsStreamStopped( PaStream *s );
208 static PaError IsStreamActive( PaStream *stream );
209 static PaTime GetStreamTime( PaStream *stream );
210 static double GetStreamCpuLoad( PaStream* stream );
211 static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
212 static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
213 static signed long GetStreamReadAvailable( PaStream* stream );
214 static signed long GetStreamWriteAvailable( PaStream* stream );
215
216
217 /* macros for setting last host error information */
218
219 #ifdef UNICODE
220
221 #define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \
222 { \
223 wchar_t mmeErrorTextWide[ MAXERRORLENGTH ]; \
224 char mmeErrorText[ MAXERRORLENGTH ]; \
225 waveInGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH ); \
226 WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\
227 mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL ); \
228 PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
229 }
230
231 #define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \
232 { \
233 wchar_t mmeErrorTextWide[ MAXERRORLENGTH ]; \
234 char mmeErrorText[ MAXERRORLENGTH ]; \
235 waveOutGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH ); \
236 WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\
237 mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL ); \
238 PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
239 }
240
241 #else /* !UNICODE */
242
243 #define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \
244 { \
245 char mmeErrorText[ MAXERRORLENGTH ]; \
246 waveInGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH ); \
247 PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
248 }
249
250 #define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \
251 { \
252 char mmeErrorText[ MAXERRORLENGTH ]; \
253 waveOutGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH ); \
254 PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
255 }
256
257 #endif /* UNICODE */
258
259
260 static void PaMme_SetLastSystemError( DWORD errorCode )
261 {
262 char *lpMsgBuf;
263 FormatMessage(
264 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
265 NULL,
266 errorCode,
267 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
268 (LPTSTR) &lpMsgBuf,
269 0,
270 NULL
271 );
272 PaUtil_SetLastHostErrorInfo( paMME, errorCode, lpMsgBuf );
273 LocalFree( lpMsgBuf );
274 }
275
276 #define PA_MME_SET_LAST_SYSTEM_ERROR( errorCode ) \
277 PaMme_SetLastSystemError( errorCode )
278
279
280 /* PaError returning wrappers for some commonly used win32 functions
281 note that we allow passing a null ptr to have no effect.
282 */
283
284 static PaError CreateEventWithPaError( HANDLE *handle,
285 LPSECURITY_ATTRIBUTES lpEventAttributes,
286 BOOL bManualReset,
287 BOOL bInitialState,
288 LPCTSTR lpName )
289 {
290 PaError result = paNoError;
291
292 *handle = NULL;
293
294 *handle = CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName );
295 if( *handle == NULL )
296 {
297 result = paUnanticipatedHostError;
298 PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
299 }
300
301 return result;
302 }
303
304
305 static PaError ResetEventWithPaError( HANDLE handle )
306 {
307 PaError result = paNoError;
308
309 if( handle )
310 {
311 if( ResetEvent( handle ) == 0 )
312 {
313 result = paUnanticipatedHostError;
314 PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
315 }
316 }
317
318 return result;
319 }
320
321
322 static PaError CloseHandleWithPaError( HANDLE handle )
323 {
324 PaError result = paNoError;
325
326 if( handle )
327 {
328 if( CloseHandle( handle ) == 0 )
329 {
330 result = paUnanticipatedHostError;
331 PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
332 }
333 }
334
335 return result;
336 }
337
338
339 /* PaWinMmeHostApiRepresentation - host api datastructure specific to this implementation */
340
341 typedef struct
342 {
343 PaUtilHostApiRepresentation inheritedHostApiRep;
344 PaUtilStreamInterface callbackStreamInterface;
345 PaUtilStreamInterface blockingStreamInterface;
346
347 PaUtilAllocationGroup *allocations;
348
349 int inputDeviceCount, outputDeviceCount;
350
351 /** winMmeDeviceIds is an array of WinMme device ids.
352 fields in the range [0, inputDeviceCount) are input device ids,
353 and [inputDeviceCount, inputDeviceCount + outputDeviceCount) are output
354 device ids.
355 */
356 UINT *winMmeDeviceIds;
357 }
358 PaWinMmeHostApiRepresentation;
359
360
361 typedef struct
362 {
363 PaDeviceInfo inheritedDeviceInfo;
364 DWORD dwFormats; /**<< standard formats bitmask from the WAVEINCAPS and WAVEOUTCAPS structures */
365 }
366 PaWinMmeDeviceInfo;
367
368
369 /*************************************************************************
370 * Returns recommended device ID.
371 * On the PC, the recommended device can be specified by the user by
372 * setting an environment variable. For example, to use device #1.
373 *
374 * set PA_RECOMMENDED_OUTPUT_DEVICE=1
375 *
376 * The user should first determine the available device ID by using
377 * the supplied application "pa_devs".
378 */
379 #define PA_ENV_BUF_SIZE_ (32)
380 #define PA_REC_IN_DEV_ENV_NAME_ ("PA_RECOMMENDED_INPUT_DEVICE")
381 #define PA_REC_OUT_DEV_ENV_NAME_ ("PA_RECOMMENDED_OUTPUT_DEVICE")
382 static PaDeviceIndex GetEnvDefaultDeviceID( char *envName )
383 {
384 PaDeviceIndex recommendedIndex = paNoDevice;
385 DWORD hresult;
386 char envbuf[PA_ENV_BUF_SIZE_];
387
388 #ifndef WIN32_PLATFORM_PSPC /* no GetEnvironmentVariable on PocketPC */
389
390 /* Let user determine default device by setting environment variable. */
391 hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE_ );
392 if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE_) )
393 {
394 recommendedIndex = atoi( envbuf );
395 }
396 #endif
397
398 return recommendedIndex;
399 }
400
401
402 static void InitializeDefaultDeviceIdsFromEnv( PaWinMmeHostApiRepresentation *hostApi )
403 {
404 PaDeviceIndex device;
405
406 /* input */
407 device = GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME_ );
408 if( device != paNoDevice &&
409 ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
410 hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxInputChannels > 0 )
411 {
412 hostApi->inheritedHostApiRep.info.defaultInputDevice = device;
413 }
414
415 /* output */
416 device = GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME_ );
417 if( device != paNoDevice &&
418 ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
419 hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxOutputChannels > 0 )
420 {
421 hostApi->inheritedHostApiRep.info.defaultOutputDevice = device;
422 }
423 }
424
425
426 /** Convert external PA ID to a windows multimedia device ID
427 */
428 static UINT LocalDeviceIndexToWinMmeDeviceId( PaWinMmeHostApiRepresentation *hostApi, PaDeviceIndex device )
429 {
430 assert( device >= 0 && device < hostApi->inputDeviceCount + hostApi->outputDeviceCount );
431
432 return hostApi->winMmeDeviceIds[ device ];
433 }
434
435
436 static PaError QueryInputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
437 {
438 MMRESULT mmresult;
439
440 switch( mmresult = waveInOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
441 {
442 case MMSYSERR_NOERROR:
443 return paNoError;
444 case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */
445 return paDeviceUnavailable;
446 case MMSYSERR_NODRIVER: /* No device driver is present. */
447 return paDeviceUnavailable;
448 case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */
449 return paInsufficientMemory;
450 case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */
451 return paSampleFormatNotSupported;
452
453 case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */
454 /* falls through */
455 default:
456 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
457 return paUnanticipatedHostError;
458 }
459 }
460
461
462 static PaError QueryOutputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
463 {
464 MMRESULT mmresult;
465
466 switch( mmresult = waveOutOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
467 {
468 case MMSYSERR_NOERROR:
469 return paNoError;
470 case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */
471 return paDeviceUnavailable;
472 case MMSYSERR_NODRIVER: /* No device driver is present. */
473 return paDeviceUnavailable;
474 case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */
475 return paInsufficientMemory;
476 case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */
477 return paSampleFormatNotSupported;
478
479 case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */
480 /* falls through */
481 default:
482 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
483 return paUnanticipatedHostError;
484 }
485 }
486
487
488 static PaError QueryFormatSupported( PaDeviceInfo *deviceInfo,
489 PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*),
490 int winMmeDeviceId, int channels, double sampleRate )
491 {
492 PaWinMmeDeviceInfo *winMmeDeviceInfo = (PaWinMmeDeviceInfo*)deviceInfo;
493 WAVEFORMATEX waveFormatEx;
494
495 if( sampleRate == 11025.0
496 && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16))
497 || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){
498
499 return paNoError;
500 }
501
502 if( sampleRate == 22050.0
503 && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16))
504 || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){
505
506 return paNoError;
507 }
508
509 if( sampleRate == 44100.0
510 && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16))
511 || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){
512
513 return paNoError;
514 }
515
516 waveFormatEx.wFormatTag = WAVE_FORMAT_PCM;
517 waveFormatEx.nChannels = (WORD)channels;
518 waveFormatEx.nSamplesPerSec = (DWORD)sampleRate;
519 waveFormatEx.nAvgBytesPerSec = waveFormatEx.nSamplesPerSec * channels * sizeof(short);
520 waveFormatEx.nBlockAlign = (WORD)(channels * sizeof(short));
521 waveFormatEx.wBitsPerSample = 16;
522 waveFormatEx.cbSize = 0;
523
524 return waveFormatExQueryFunction( winMmeDeviceId, &waveFormatEx );
525 }
526
527
528 #define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ (13) /* must match array length below */
529 static double defaultSampleRateSearchOrder_[] =
530 { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
531 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
532
533 static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int winMmeDeviceId,
534 PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*), int maxChannels )
535 {
536 PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
537 int i;
538
539 deviceInfo->defaultSampleRate = 0.;
540
541 for( i=0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
542 {
543 double sampleRate = defaultSampleRateSearchOrder_[ i ];
544 PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate );
545 if( paerror == paNoError )
546 {
547 deviceInfo->defaultSampleRate = sampleRate;
548 break;
549 }
550 }
551 }
552
553
554 static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
555 PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeInputDeviceId, int *success )
556 {
557 PaError result = paNoError;
558 char *deviceName; /* non-const ptr */
559 MMRESULT mmresult;
560 WAVEINCAPS wic;
561 PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
562
563 *success = 0;
564
565 mmresult = waveInGetDevCaps( winMmeInputDeviceId, &wic, sizeof( WAVEINCAPS ) );
566 if( mmresult == MMSYSERR_NOMEM )
567 {
568 result = paInsufficientMemory;
569 goto error;
570 }
571 else if( mmresult != MMSYSERR_NOERROR )
572 {
573 /* instead of returning paUnanticipatedHostError we return
574 paNoError, but leave success set as 0. This allows
575 Pa_Initialize to just ignore this device, without failing
576 the entire initialisation process.
577 */
578 return paNoError;
579 }
580
581 if( winMmeInputDeviceId == WAVE_MAPPER )
582 {
583 /* Append I/O suffix to WAVE_MAPPER device. */
584 deviceName = (char *)PaUtil_GroupAllocateMemory(
585 winMmeHostApi->allocations, strlen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_) );
586 if( !deviceName )
587 {
588 result = paInsufficientMemory;
589 goto error;
590 }
591 strcpy( deviceName, wic.szPname );
592 strcat( deviceName, constInputMapperSuffix_ );
593 }
594 else
595 {
596 deviceName = (char*)PaUtil_GroupAllocateMemory(
597 winMmeHostApi->allocations, strlen( wic.szPname ) + 1 );
598 if( !deviceName )
599 {
600 result = paInsufficientMemory;
601 goto error;
602 }
603 strcpy( deviceName, wic.szPname );
604 }
605 deviceInfo->name = deviceName;
606
607 deviceInfo->maxInputChannels = wic.wChannels;
608 /* Sometimes a device can return a rediculously large number of channels.
609 * This happened with an SBLive card on a Windows ME box.
610 * If that happens, then force it to 2 channels. PLB20010413
611 */
612 if( (deviceInfo->maxInputChannels < 1) || (deviceInfo->maxInputChannels > 256) )
613 {
614 PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", deviceInfo->maxInputChannels ));
615 deviceInfo->maxInputChannels = 2;
616 }
617
618 winMmeDeviceInfo->dwFormats = wic.dwFormats;
619
620 DetectDefaultSampleRate( winMmeDeviceInfo, winMmeInputDeviceId,
621 QueryInputWaveFormatEx, deviceInfo->maxInputChannels );
622
623 *success = 1;
624
625 error:
626 return result;
627 }
628
629
630 static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
631 PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeOutputDeviceId, int *success )
632 {
633 PaError result = paNoError;
634 char *deviceName; /* non-const ptr */
635 MMRESULT mmresult;
636 WAVEOUTCAPS woc;
637 PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
638
639 *success = 0;
640
641 mmresult = waveOutGetDevCaps( winMmeOutputDeviceId, &woc, sizeof( WAVEOUTCAPS ) );
642 if( mmresult == MMSYSERR_NOMEM )
643 {
644 result = paInsufficientMemory;
645 goto error;
646 }
647 else if( mmresult != MMSYSERR_NOERROR )
648 {
649 /* instead of returning paUnanticipatedHostError we return
650 paNoError, but leave success set as 0. This allows
651 Pa_Initialize to just ignore this device, without failing
652 the entire initialisation process.
653 */
654 return paNoError;
655 }
656
657 if( winMmeOutputDeviceId == WAVE_MAPPER )
658 {
659 /* Append I/O suffix to WAVE_MAPPER device. */
660 deviceName = (char *)PaUtil_GroupAllocateMemory(
661 winMmeHostApi->allocations, strlen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_) );
662 if( !deviceName )
663 {
664 result = paInsufficientMemory;
665 goto error;
666 }
667 strcpy( deviceName, woc.szPname );
668 strcat( deviceName, constOutputMapperSuffix_ );
669 }
670 else
671 {
672 deviceName = (char*)PaUtil_GroupAllocateMemory(
673 winMmeHostApi->allocations, strlen( woc.szPname ) + 1 );
674 if( !deviceName )
675 {
676 result = paInsufficientMemory;
677 goto error;
678 }
679 strcpy( deviceName, woc.szPname );
680 }
681 deviceInfo->name = deviceName;
682
683 deviceInfo->maxOutputChannels = woc.wChannels;
684 /* Sometimes a device can return a rediculously large number of channels.
685 * This happened with an SBLive card on a Windows ME box.
686 * It also happens on Win XP!
687 */
688 if( (deviceInfo->maxOutputChannels < 1) || (deviceInfo->maxOutputChannels > 256) )
689 {
690 PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", deviceInfo->maxOutputChannels ));
691 deviceInfo->maxOutputChannels = 2;
692 }
693
694 winMmeDeviceInfo->dwFormats = woc.dwFormats;
695
696 DetectDefaultSampleRate( winMmeDeviceInfo, winMmeOutputDeviceId,
697 QueryOutputWaveFormatEx, deviceInfo->maxOutputChannels );
698
699 *success = 1;
700
701 error:
702 return result;
703 }
704
705
706 static void GetDefaultLatencies( PaTime *defaultLowLatency, PaTime *defaultHighLatency )
707 {
708 OSVERSIONINFO osvi;
709 osvi.dwOSVersionInfoSize = sizeof( osvi );
710 GetVersionEx( &osvi );
711
712 /* Check for NT */
713 if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
714 {
715 *defaultLowLatency = PA_MME_WIN_NT_DEFAULT_LATENCY_;
716 }
717 else if(osvi.dwMajorVersion >= 5)
718 {
719 *defaultLowLatency = PA_MME_WIN_WDM_DEFAULT_LATENCY_;
720 }
721 else
722 {
723 *defaultLowLatency = PA_MME_WIN_9X_DEFAULT_LATENCY_;
724 }
725
726 *defaultHighLatency = *defaultLowLatency * 2;
727 }
728
729
730 PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
731 {
732 PaError result = paNoError;
733 int i;
734 PaWinMmeHostApiRepresentation *winMmeHostApi;
735 int inputDeviceCount, outputDeviceCount, maximumPossibleDeviceCount;
736 PaWinMmeDeviceInfo *deviceInfoArray;
737 int deviceInfoInitializationSucceeded;
738 PaTime defaultLowLatency, defaultHighLatency;
739
740 winMmeHostApi = (PaWinMmeHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinMmeHostApiRepresentation) );
741 if( !winMmeHostApi )
742 {
743 result = paInsufficientMemory;
744 goto error;
745 }
746
747 winMmeHostApi->allocations = PaUtil_CreateAllocationGroup();
748 if( !winMmeHostApi->allocations )
749 {
750 result = paInsufficientMemory;
751 goto error;
752 }
753
754 *hostApi = &winMmeHostApi->inheritedHostApiRep;
755 (*hostApi)->info.structVersion = 1;
756 (*hostApi)->info.type = paMME;
757 (*hostApi)->info.name = "MME";
758
759
760 /* initialise device counts and default devices under the assumption that
761 there are no devices. These values are incremented below if and when
762 devices are successfully initialized.
763 */
764 (*hostApi)->info.deviceCount = 0;
765 (*hostApi)->info.defaultInputDevice = paNoDevice;
766 (*hostApi)->info.defaultOutputDevice = paNoDevice;
767 winMmeHostApi->inputDeviceCount = 0;
768 winMmeHostApi->outputDeviceCount = 0;
769
770
771 maximumPossibleDeviceCount = 0;
772
773 inputDeviceCount = waveInGetNumDevs();
774 if( inputDeviceCount > 0 )
775 maximumPossibleDeviceCount += inputDeviceCount + 1; /* assume there is a WAVE_MAPPER */
776
777 outputDeviceCount = waveOutGetNumDevs();
778 if( outputDeviceCount > 0 )
779 maximumPossibleDeviceCount += outputDeviceCount + 1; /* assume there is a WAVE_MAPPER */
780
781
782 if( maximumPossibleDeviceCount > 0 ){
783
784 (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
785 winMmeHostApi->allocations, sizeof(PaDeviceInfo*) * maximumPossibleDeviceCount );
786 if( !(*hostApi)->deviceInfos )
787 {
788 result = paInsufficientMemory;
789 goto error;
790 }
791
792 /* allocate all device info structs in a contiguous block */
793 deviceInfoArray = (PaWinMmeDeviceInfo*)PaUtil_GroupAllocateMemory(
794 winMmeHostApi->allocations, sizeof(PaWinMmeDeviceInfo) * maximumPossibleDeviceCount );
795 if( !deviceInfoArray )
796 {
797 result = paInsufficientMemory;
798 goto error;
799 }
800
801 winMmeHostApi->winMmeDeviceIds = (UINT*)PaUtil_GroupAllocateMemory(
802 winMmeHostApi->allocations, sizeof(int) * maximumPossibleDeviceCount );
803 if( !winMmeHostApi->winMmeDeviceIds )
804 {
805 result = paInsufficientMemory;
806 goto error;
807 }
808
809 GetDefaultLatencies( &defaultLowLatency, &defaultHighLatency );
810
811 if( inputDeviceCount > 0 ){
812 /* -1 is the WAVE_MAPPER */
813 for( i = -1; i < inputDeviceCount; ++i ){
814 UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
815 PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
816 PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
817 deviceInfo->structVersion = 2;
818 deviceInfo->hostApi = hostApiIndex;
819
820 deviceInfo->maxInputChannels = 0;
821 deviceInfo->maxOutputChannels = 0;
822
823 deviceInfo->defaultLowInputLatency = defaultLowLatency;
824 deviceInfo->defaultLowOutputLatency = defaultLowLatency;
825 deviceInfo->defaultHighInputLatency = defaultHighLatency;
826 deviceInfo->defaultHighOutputLatency = defaultHighLatency;
827
828 result = InitializeInputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
829 winMmeDeviceId, &deviceInfoInitializationSucceeded );
830 if( result != paNoError )
831 goto error;
832
833 if( deviceInfoInitializationSucceeded ){
834 if( (*hostApi)->info.defaultInputDevice == paNoDevice )
835 (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
836
837 winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
838 (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
839
840 winMmeHostApi->inputDeviceCount++;
841 (*hostApi)->info.deviceCount++;
842 }
843 }
844 }
845
846 if( outputDeviceCount > 0 ){
847 /* -1 is the WAVE_MAPPER */
848 for( i = -1; i < outputDeviceCount; ++i ){
849 UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
850 PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
851 PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
852 deviceInfo->structVersion = 2;
853 deviceInfo->hostApi = hostApiIndex;
854
855 deviceInfo->maxInputChannels = 0;
856 deviceInfo->maxOutputChannels = 0;
857
858 deviceInfo->defaultLowInputLatency = defaultLowLatency;
859 deviceInfo->defaultLowOutputLatency = defaultLowLatency;
860 deviceInfo->defaultHighInputLatency = defaultHighLatency;
861 deviceInfo->defaultHighOutputLatency = defaultHighLatency;
862
863 result = InitializeOutputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
864 winMmeDeviceId, &deviceInfoInitializationSucceeded );
865 if( result != paNoError )
866 goto error;
867
868 if( deviceInfoInitializationSucceeded ){
869 if( (*hostApi)->info.defaultOutputDevice == paNoDevice )
870 (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
871
872 winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
873 (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
874
875 winMmeHostApi->outputDeviceCount++;
876 (*hostApi)->info.deviceCount++;
877 }
878 }
879 }
880 }
881
882
883 InitializeDefaultDeviceIdsFromEnv( winMmeHostApi );
884
885 (*hostApi)->Terminate = Terminate;
886 (*hostApi)->OpenStream = OpenStream;
887 (*hostApi)->IsFormatSupported = IsFormatSupported;
888
889 PaUtil_InitializeStreamInterface( &winMmeHostApi->callbackStreamInterface, CloseStream, StartStream,
890 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
891 GetStreamTime, GetStreamCpuLoad,
892 PaUtil_DummyRead, PaUtil_DummyWrite,
893 PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
894
895 PaUtil_InitializeStreamInterface( &winMmeHostApi->blockingStreamInterface, CloseStream, StartStream,
896 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
897 GetStreamTime, PaUtil_DummyGetCpuLoad,
898 ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
899
900 return result;
901
902 error:
903 if( winMmeHostApi )
904 {
905 if( winMmeHostApi->allocations )
906 {
907 PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
908 PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
909 }
910
911 PaUtil_FreeMemory( winMmeHostApi );
912 }
913
914 return result;
915 }
916
917
918 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
919 {
920 PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
921
922 if( winMmeHostApi->allocations )
923 {
924 PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
925 PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
926 }
927
928 PaUtil_FreeMemory( winMmeHostApi );
929 }
930
931
932 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
933 const PaStreamParameters *inputParameters,
934 const PaStreamParameters *outputParameters,
935 double sampleRate )
936 {
937 PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
938 PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
939 int inputChannelCount, outputChannelCount;
940 int inputMultipleDeviceChannelCount, outputMultipleDeviceChannelCount;
941 PaSampleFormat inputSampleFormat, outputSampleFormat;
942 PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
943 UINT winMmeInputDeviceId, winMmeOutputDeviceId;
944 unsigned int i;
945 PaError paerror;
946
947 /* The calls to QueryFormatSupported below are intended to detect invalid
948 sample rates. If we assume that the channel count and format are OK,
949 then the only thing that could fail is the sample rate. This isn't
950 strictly true, but I can't think of a better way to test that the
951 sample rate is valid.
952 */
953
954 if( inputParameters )
955 {
956 inputChannelCount = inputParameters->channelCount;
957 inputSampleFormat = inputParameters->sampleFormat;
958 inputStreamInfo = inputParameters->hostApiSpecificStreamInfo;
959
960 /* all standard sample formats are supported by the buffer adapter,
961 this implementation doesn't support any custom sample formats */
962 if( inputSampleFormat & paCustomFormat )
963 return paSampleFormatNotSupported;
964
965 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification
966 && inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
967 {
968 inputMultipleDeviceChannelCount = 0;
969 for( i=0; i< inputStreamInfo->deviceCount; ++i )
970 {
971 inputMultipleDeviceChannelCount += inputStreamInfo->devices[i].channelCount;
972
973 inputDeviceInfo = hostApi->deviceInfos[ inputStreamInfo->devices[i].device ];
974
975 /* check that input device can support inputChannelCount */
976 if( inputStreamInfo->devices[i].channelCount <= 0
977 || inputStreamInfo->devices[i].channelCount > inputDeviceInfo->maxInputChannels )
978 return paInvalidChannelCount;
979
980 /* test for valid sample rate, see comment above */
981 winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputStreamInfo->devices[i].device );
982 paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate );
983 if( paerror != paNoError )
984 return paInvalidSampleRate;
985 }
986
987 if( inputMultipleDeviceChannelCount != inputChannelCount )
988 return paIncompatibleHostApiSpecificStreamInfo;
989 }
990 else
991 {
992 if( inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
993 return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the input device */
994
995 inputDeviceInfo = hostApi->deviceInfos[ inputParameters->device ];
996
997 /* check that input device can support inputChannelCount */
998 if( inputChannelCount > inputDeviceInfo->maxInputChannels )
999 return paInvalidChannelCount;
1000
1001 /* test for valid sample rate, see comment above */
1002 winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputParameters->device );
1003 paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputChannelCount, sampleRate );
1004 if( paerror != paNoError )
1005 return paInvalidSampleRate;
1006 }
1007 }
1008
1009 if( outputParameters )
1010 {
1011 outputChannelCount = outputParameters->channelCount;
1012 outputSampleFormat = outputParameters->sampleFormat;
1013 outputStreamInfo = outputParameters->hostApiSpecificStreamInfo;
1014
1015 /* all standard sample formats are supported by the buffer adapter,
1016 this implementation doesn't support any custom sample formats */
1017 if( outputSampleFormat & paCustomFormat )
1018 return paSampleFormatNotSupported;
1019
1020 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification
1021 && outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
1022 {
1023 outputMultipleDeviceChannelCount = 0;
1024 for( i=0; i< outputStreamInfo->deviceCount; ++i )
1025 {
1026 outputMultipleDeviceChannelCount += outputStreamInfo->devices[i].channelCount;
1027
1028 outputDeviceInfo = hostApi->deviceInfos[ outputStreamInfo->devices[i].device ];
1029
1030 /* check that output device can support outputChannelCount */
1031 if( outputStreamInfo->devices[i].channelCount <= 0
1032 || outputStreamInfo->devices[i].channelCount > outputDeviceInfo->maxOutputChannels )
1033 return paInvalidChannelCount;
1034
1035 /* test for valid sample rate, see comment above */
1036 winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputStreamInfo->devices[i].device );
1037 paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate );
1038 if( paerror != paNoError )
1039 return paInvalidSampleRate;
1040 }
1041
1042 if( outputMultipleDeviceChannelCount != outputChannelCount )
1043 return paIncompatibleHostApiSpecificStreamInfo;
1044 }
1045 else
1046 {
1047 if( outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
1048 return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the output device */
1049
1050 outputDeviceInfo = hostApi->deviceInfos[ outputParameters->device ];
1051
1052 /* check that output device can support outputChannelCount */
1053 if( outputChannelCount > outputDeviceInfo->maxOutputChannels )
1054 return paInvalidChannelCount;
1055
1056 /* test for valid sample rate, see comment above */
1057 winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputParameters->device );
1058 paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputChannelCount, sampleRate );
1059 if( paerror != paNoError )
1060 return paInvalidSampleRate;
1061 }
1062 }
1063
1064 /*
1065 - if a full duplex stream is requested, check that the combination
1066 of input and output parameters is supported
1067
1068 - check that the device supports sampleRate
1069
1070 for mme all we can do is test that the input and output devices
1071 support the requested sample rate and number of channels. we
1072 cannot test for full duplex compatibility.
1073 */
1074
1075 return paFormatIsSupported;
1076 }
1077
1078
1079
1080 static void SelectBufferSizeAndCount( unsigned long baseBufferSize,
1081 unsigned long requestedLatency,
1082 unsigned long baseBufferCount, unsigned long minimumBufferCount,
1083 unsigned long maximumBufferSize, unsigned long *hostBufferSize,
1084 unsigned long *hostBufferCount )
1085 {
1086 unsigned long sizeMultiplier, bufferCount, latency;
1087 unsigned long nextLatency, nextBufferSize;
1088 int baseBufferSizeIsPowerOfTwo;
1089
1090 sizeMultiplier = 1;
1091 bufferCount = baseBufferCount;
1092
1093 /* count-1 below because latency is always determined by one less
1094 than the total number of buffers.
1095 */
1096 latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1);
1097
1098 if( latency > requestedLatency )
1099 {
1100
1101 /* reduce number of buffers without falling below suggested latency */
1102
1103 nextLatency = (baseBufferSize * sizeMultiplier) * (bufferCount-2);
1104 while( bufferCount > minimumBufferCount && nextLatency >= requestedLatency )
1105 {
1106 --bufferCount;
1107 nextLatency = (baseBufferSize * sizeMultiplier) * (bufferCount-2);
1108 }
1109
1110 }else if( latency < requestedLatency ){
1111
1112 baseBufferSizeIsPowerOfTwo = (! (baseBufferSize & (baseBufferSize - 1)));
1113 if( baseBufferSizeIsPowerOfTwo ){
1114
1115 /* double size of buffers without exceeding requestedLatency */
1116
1117 nextBufferSize = (baseBufferSize * (sizeMultiplier*2));
1118 nextLatency = nextBufferSize * (bufferCount-1);
1119 while( nextBufferSize <= maximumBufferSize
1120 && nextLatency < requestedLatency )
1121 {
1122 sizeMultiplier *= 2;
1123 nextBufferSize = (baseBufferSize * (sizeMultiplier*2));
1124 nextLatency = nextBufferSize * (bufferCount-1);
1125 }
1126
1127 }else{
1128
1129 /* increase size of buffers upto first excess of requestedLatency */
1130
1131 nextBufferSize = (baseBufferSize * (sizeMultiplier+1));
1132 nextLatency = nextBufferSize * (bufferCount-1);
1133 while( nextBufferSize <= maximumBufferSize
1134 && nextLatency < requestedLatency )
1135 {
1136 ++sizeMultiplier;
1137 nextBufferSize = (baseBufferSize * (sizeMultiplier+1));
1138 nextLatency = nextBufferSize * (bufferCount-1);
1139 }
1140
1141 if( nextLatency < requestedLatency )
1142 ++sizeMultiplier;
1143 }
1144
1145 /* increase number of buffers until requestedLatency is reached */
1146
1147 latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1);
1148 while( latency < requestedLatency )
1149 {
1150 ++bufferCount;
1151 latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1);
1152 }
1153 }
1154
1155 *hostBufferSize = baseBufferSize * sizeMultiplier;
1156 *hostBufferCount = bufferCount;
1157 }
1158
1159
1160 static void ReselectBufferCount( unsigned long bufferSize,
1161 unsigned long requestedLatency,
1162 unsigned long baseBufferCount, unsigned long minimumBufferCount,
1163 unsigned long *hostBufferCount )
1164 {
1165 unsigned long bufferCount, latency;
1166 unsigned long nextLatency;
1167
1168 bufferCount = baseBufferCount;
1169
1170 /* count-1 below because latency is always determined by one less
1171 than the total number of buffers.
1172 */
1173 latency = bufferSize * (bufferCount-1);
1174
1175 if( latency > requestedLatency )
1176 {
1177 /* reduce number of buffers without falling below suggested latency */
1178
1179 nextLatency = bufferSize * (bufferCount-2);
1180 while( bufferCount > minimumBufferCount && nextLatency >= requestedLatency )
1181 {
1182 --bufferCount;
1183 nextLatency = bufferSize * (bufferCount-2);
1184 }
1185
1186 }else if( latency < requestedLatency ){
1187
1188 /* increase number of buffers until requestedLatency is reached */
1189
1190 latency = bufferSize * (bufferCount-1);
1191 while( latency < requestedLatency )
1192 {
1193 ++bufferCount;
1194 latency = bufferSize * (bufferCount-1);
1195 }
1196 }
1197
1198 *hostBufferCount = bufferCount;
1199 }
1200
1201
1202 /* CalculateBufferSettings() fills the framesPerHostInputBuffer, hostInputBufferCount,
1203 framesPerHostOutputBuffer and hostOutputBufferCount parameters based on the values
1204 of the other parameters.
1205 */
1206
1207 static PaError CalculateBufferSettings(
1208 unsigned long *framesPerHostInputBuffer, unsigned long *hostInputBufferCount,
1209 unsigned long *framesPerHostOutputBuffer, unsigned long *hostOutputBufferCount,
1210 int inputChannelCount, PaSampleFormat hostInputSampleFormat,
1211 PaTime suggestedInputLatency, PaWinMmeStreamInfo *inputStreamInfo,
1212 int outputChannelCount, PaSampleFormat hostOutputSampleFormat,
1213 PaTime suggestedOutputLatency, PaWinMmeStreamInfo *outputStreamInfo,
1214 double sampleRate, unsigned long framesPerBuffer )
1215 {
1216 PaError result = paNoError;
1217 int effectiveInputChannelCount, effectiveOutputChannelCount;
1218 int hostInputFrameSize = 0;
1219 unsigned int i;
1220
1221 if( inputChannelCount > 0 )
1222 {
1223 int hostInputSampleSize = Pa_GetSampleSize( hostInputSampleFormat );
1224 if( hostInputSampleSize < 0 )
1225 {
1226 result = hostInputSampleSize;
1227 goto error;
1228 }
1229
1230 if( inputStreamInfo
1231 && ( inputStreamInfo->flags & paWinMmeUseMultipleDevices ) )
1232 {
1233 /* set effectiveInputChannelCount to the largest number of
1234 channels on any one device.
1235 */
1236 effectiveInputChannelCount = 0;
1237 for( i=0; i< inputStreamInfo->deviceCount; ++i )
1238 {
1239 if( inputStreamInfo->devices[i].channelCount > effectiveInputChannelCount )
1240 effectiveInputChannelCount = inputStreamInfo->devices[i].channelCount;
1241 }
1242 }
1243 else
1244 {
1245 effectiveInputChannelCount = inputChannelCount;
1246 }
1247
1248 hostInputFrameSize = hostInputSampleSize * effectiveInputChannelCount;
1249
1250 if( inputStreamInfo
1251 && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
1252 {
1253 if( inputStreamInfo->bufferCount <= 0
1254 || inputStreamInfo->framesPerBuffer <= 0 )
1255 {
1256 result = paIncompatibleHostApiSpecificStreamInfo;
1257 goto error;
1258 }
1259
1260 *framesPerHostInputBuffer = inputStreamInfo->framesPerBuffer;
1261 *hostInputBufferCount = inputStreamInfo->bufferCount;
1262 }
1263 else
1264 {
1265 unsigned long hostBufferSizeBytes, hostBufferCount;
1266 unsigned long minimumBufferCount = (outputChannelCount > 0)
1267 ? PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_
1268 : PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_;
1269
1270 unsigned long maximumBufferSize = (long) ((PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate) * hostInputFrameSize);
1271 if( maximumBufferSize > PA_MME_MAX_HOST_BUFFER_BYTES_ )
1272 maximumBufferSize = PA_MME_MAX_HOST_BUFFER_BYTES_;
1273
1274 /* compute the following in bytes, then convert back to frames */
1275
1276 SelectBufferSizeAndCount(
1277 ((framesPerBuffer == paFramesPerBufferUnspecified)
1278 ? PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_
1279 : framesPerBuffer ) * hostInputFrameSize, /* baseBufferSize */
1280 ((unsigned long)(suggestedInputLatency * sampleRate)) * hostInputFrameSize, /* suggestedLatency */
1281 4, /* baseBufferCount */
1282 minimumBufferCount, maximumBufferSize,
1283 &hostBufferSizeBytes, &hostBufferCount );
1284
1285 *framesPerHostInputBuffer = hostBufferSizeBytes / hostInputFrameSize;
1286 *hostInputBufferCount = hostBufferCount;
1287 }
1288 }
1289 else
1290 {
1291 *framesPerHostInputBuffer = 0;
1292 *hostInputBufferCount = 0;
1293 }
1294
1295 if( outputChannelCount > 0 )
1296 {
1297 if( outputStreamInfo
1298 && ( outputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
1299 {
1300 if( outputStreamInfo->bufferCount <= 0
1301 || outputStreamInfo->framesPerBuffer <= 0 )
1302 {
1303 result = paIncompatibleHostApiSpecificStreamInfo;
1304 goto error;
1305 }
1306
1307 *framesPerHostOutputBuffer = outputStreamInfo->framesPerBuffer;
1308 *hostOutputBufferCount = outputStreamInfo->bufferCount;
1309
1310
1311 if( inputChannelCount > 0 ) /* full duplex */
1312 {
1313 if( *framesPerHostInputBuffer != *framesPerHostOutputBuffer )
1314 {
1315 if( inputStreamInfo
1316 && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
1317 {
1318 /* a custom StreamInfo was used for specifying both input
1319 and output buffer sizes, the larger buffer size
1320 must be a multiple of the smaller buffer size */
1321
1322 if( *framesPerHostInputBuffer < *framesPerHostOutputBuffer )
1323 {
1324 if( *framesPerHostOutputBuffer % *framesPerHostInputBuffer != 0 )
1325 {
1326 result = paIncompatibleHostApiSpecificStreamInfo;
1327 goto error;
1328 }
1329 }
1330 else
1331 {
1332 assert( *framesPerHostInputBuffer > *framesPerHostOutputBuffer );
1333 if( *framesPerHostInputBuffer % *framesPerHostOutputBuffer != 0 )
1334 {
1335 result = paIncompatibleHostApiSpecificStreamInfo;
1336 goto error;
1337 }
1338 }
1339 }
1340 else
1341 {
1342 /* a custom StreamInfo was not used for specifying the input buffer size,
1343 so use the output buffer size, and approximately the same latency. */
1344
1345 *framesPerHostInputBuffer = *framesPerHostOutputBuffer;
1346 *hostInputBufferCount = (((unsigned long)(suggestedInputLatency * sampleRate)) / *framesPerHostInputBuffer) + 1;
1347
1348 if( *hostInputBufferCount < PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ )
1349 *hostInputBufferCount = PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_;
1350 }
1351 }
1352 }
1353 }
1354 else
1355 {
1356 unsigned long hostBufferSizeBytes, hostBufferCount;
1357 unsigned long minimumBufferCount = PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_;
1358 unsigned long maximumBufferSize;
1359 int hostOutputFrameSize;
1360 int hostOutputSampleSize;
1361
1362 hostOutputSampleSize = Pa_GetSampleSize( hostOutputSampleFormat );
1363 if( hostOutputSampleSize < 0 )
1364 {
1365 result = hostOutputSampleSize;
1366 goto error;
1367 }
1368
1369 if( outputStreamInfo
1370 && ( outputStreamInfo->flags & paWinMmeUseMultipleDevices ) )
1371 {
1372 /* set effectiveOutputChannelCount to the largest number of
1373 channels on any one device.
1374 */
1375 effectiveOutputChannelCount = 0;
1376 for( i=0; i< outputStreamInfo->deviceCount; ++i )
1377 {
1378 if( outputStreamInfo->devices[i].channelCount > effectiveOutputChannelCount )
1379 effectiveOutputChannelCount = outputStreamInfo->devices[i].channelCount;
1380 }
1381 }
1382 else
1383 {
1384 effectiveOutputChannelCount = outputChannelCount;
1385 }
1386
1387 hostOutputFrameSize = hostOutputSampleSize * effectiveOutputChannelCount;
1388
1389 maximumBufferSize = (long) ((PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate) * hostOutputFrameSize);
1390 if( maximumBufferSize > PA_MME_MAX_HOST_BUFFER_BYTES_ )
1391 maximumBufferSize = PA_MME_MAX_HOST_BUFFER_BYTES_;
1392
1393
1394 /* compute the following in bytes, then convert back to frames */
1395
1396 SelectBufferSizeAndCount(
1397 ((framesPerBuffer == paFramesPerBufferUnspecified)
1398 ? PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_
1399 : framesPerBuffer ) * hostOutputFrameSize, /* baseBufferSize */
1400 ((unsigned long)(suggestedOutputLatency * sampleRate)) * hostOutputFrameSize, /* suggestedLatency */
1401 4, /* baseBufferCount */
1402 minimumBufferCount,
1403 maximumBufferSize,
1404 &hostBufferSizeBytes, &hostBufferCount );
1405
1406 *framesPerHostOutputBuffer = hostBufferSizeBytes / hostOutputFrameSize;
1407 *hostOutputBufferCount = hostBufferCount;
1408
1409
1410 if( inputChannelCount > 0 )
1411 {
1412 /* ensure that both input and output buffer sizes are the same.
1413 if they don't match at this stage, choose the smallest one
1414 and use that for input and output
1415 */
1416
1417 if( *framesPerHostOutputBuffer != *framesPerHostInputBuffer )
1418 {
1419 if( framesPerHostInputBuffer < framesPerHostOutputBuffer )
1420 {
1421 unsigned long framesPerHostBuffer = *framesPerHostInputBuffer;
1422
1423 minimumBufferCount = PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_;
1424 ReselectBufferCount(
1425 framesPerHostBuffer * hostOutputFrameSize, /* bufferSize */
1426 ((unsigned long)(suggestedOutputLatency * sampleRate)) * hostOutputFrameSize, /* suggestedLatency */
1427 4, /* baseBufferCount */
1428 minimumBufferCount,
1429 &hostBufferCount );
1430
1431 *framesPerHostOutputBuffer = framesPerHostBuffer;
1432 *hostOutputBufferCount = hostBufferCount;
1433 }
1434 else
1435 {
1436 unsigned long framesPerHostBuffer = *framesPerHostOutputBuffer;
1437
1438 minimumBufferCount = PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_;
1439 ReselectBufferCount(
1440 framesPerHostBuffer * hostInputFrameSize, /* bufferSize */
1441 ((unsigned long)(suggestedInputLatency * sampleRate)) * hostInputFrameSize, /* suggestedLatency */
1442 4, /* baseBufferCount */
1443 minimumBufferCount,
1444 &hostBufferCount );
1445
1446 *framesPerHostInputBuffer = framesPerHostBuffer;
1447 *hostInputBufferCount = hostBufferCount;
1448 }
1449 }
1450 }
1451 }
1452 }
1453 else
1454 {
1455 *framesPerHostOutputBuffer = 0;
1456 *hostOutputBufferCount = 0;
1457 }
1458
1459 error:
1460 return result;
1461 }
1462
1463
1464 typedef struct
1465 {
1466 HANDLE bufferEvent;
1467 void *waveHandles;
1468 unsigned int deviceCount;
1469 /* unsigned int channelCount; */
1470 WAVEHDR **waveHeaders; /* waveHeaders[device][buffer] */
1471 unsigned int bufferCount;
1472 unsigned int currentBufferIndex;
1473 unsigned int framesPerBuffer;
1474 unsigned int framesUsedInCurrentBuffer;
1475 }PaWinMmeSingleDirectionHandlesAndBuffers;
1476
1477 /* prototypes for functions operating on PaWinMmeSingleDirectionHandlesAndBuffers */
1478
1479 static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers );
1480 static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
1481 PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
1482 unsigned long bytesPerHostSample,
1483 double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
1484 unsigned int deviceCount, int isInput );
1485 static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError );
1486 static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
1487 unsigned long hostBufferCount,
1488 PaSampleFormat hostSampleFormat,
1489 unsigned long framesPerHostBuffer,
1490 PaWinMmeDeviceAndChannelCount *devices,
1491 int isInput );
1492 static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput );
1493
1494
1495 static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
1496 {
1497 handlesAndBuffers->bufferEvent = 0;
1498 handlesAndBuffers->waveHandles = 0;
1499 handlesAndBuffers->deviceCount = 0;
1500 handlesAndBuffers->waveHeaders = 0;
1501 handlesAndBuffers->bufferCount = 0;
1502 }
1503
1504 static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
1505 PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
1506 unsigned long bytesPerHostSample,
1507 double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
1508 unsigned int deviceCount, int isInput )
1509 {
1510 PaError result;
1511 MMRESULT mmresult;
1512 unsigned long bytesPerFrame;
1513 WAVEFORMATEX wfx;
1514 signed int i;
1515
1516 /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
1517 has already been called to zero some fields */
1518
1519 result = CreateEventWithPaError( &handlesAndBuffers->bufferEvent, NULL, FALSE, FALSE, NULL );
1520 if( result != paNoError ) goto error;
1521
1522 if( isInput )
1523 handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEIN) * deviceCount );
1524 else
1525 handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEOUT) * deviceCount );
1526 if( !handlesAndBuffers->waveHandles )
1527 {
1528 result = paInsufficientMemory;
1529 goto error;
1530 }
1531
1532 handlesAndBuffers->deviceCount = deviceCount;
1533
1534 for( i = 0; i < (signed int)deviceCount; ++i )
1535 {
1536 if( isInput )
1537 ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] = 0;
1538 else
1539 ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] = 0;
1540 }
1541
1542 wfx.wFormatTag = WAVE_FORMAT_PCM;
1543 wfx.nSamplesPerSec = (DWORD) sampleRate;
1544 wfx.cbSize = 0;
1545
1546 for( i = 0; i < (signed int)deviceCount; ++i )
1547 {
1548 UINT winMmeDeviceId;
1549
1550 winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device );
1551 wfx.nChannels = (WORD)devices[i].channelCount;
1552
1553 bytesPerFrame = wfx.nChannels * bytesPerHostSample;
1554
1555 wfx.nAvgBytesPerSec = (DWORD)(bytesPerFrame * sampleRate);
1556 wfx.nBlockAlign = (WORD)bytesPerFrame;
1557 wfx.wBitsPerSample = (WORD)((bytesPerFrame/wfx.nChannels) * 8);
1558
1559 /* REVIEW: consider not firing an event for input when a full duplex
1560 stream is being used. this would probably depend on the
1561 neverDropInput flag. */
1562
1563 if( isInput )
1564 mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx,
1565 (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
1566 else
1567 mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx,
1568 (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
1569
1570 if( mmresult != MMSYSERR_NOERROR )
1571 {
1572 switch( mmresult )
1573 {
1574 case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */
1575 result = paDeviceUnavailable;
1576 break;
1577 case MMSYSERR_NODRIVER: /* No device driver is present. */
1578 result = paDeviceUnavailable;
1579 break;
1580 case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */
1581 result = paInsufficientMemory;
1582 break;
1583
1584 case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */
1585 /* falls through */
1586 case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */
1587 /* falls through */
1588 default:
1589 result = paUnanticipatedHostError;
1590 if( isInput )
1591 {
1592 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
1593 }
1594 else
1595 {
1596 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
1597 }
1598 }
1599 goto error;
1600 }
1601 }
1602
1603 return result;
1604
1605 error:
1606 TerminateWaveHandles( handlesAndBuffers, isInput, 1 /* currentlyProcessingAnError */ );
1607
1608 return result;
1609 }
1610
1611
1612 static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError )
1613 {
1614 PaError result = paNoError;
1615 MMRESULT mmresult;
1616 signed int i;
1617
1618 if( handlesAndBuffers->waveHandles )
1619 {
1620 for( i = handlesAndBuffers->deviceCount-1; i >= 0; --i )
1621 {
1622 if( isInput )
1623 {
1624 if( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] )
1625 mmresult = waveInClose( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] );
1626 else
1627 mmresult = MMSYSERR_NOERROR;
1628 }
1629 else
1630 {
1631 if( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] )
1632 mmresult = waveOutClose( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] );
1633 else
1634 mmresult = MMSYSERR_NOERROR;
1635 }
1636
1637 if( mmresult != MMSYSERR_NOERROR &&
1638 !currentlyProcessingAnError ) /* don't update the error state if we're already processing an error */
1639 {
1640 result = paUnanticipatedHostError;
1641 if( isInput )
1642 {
1643 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
1644 }
1645 else
1646 {
1647 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
1648 }
1649 /* note that we don't break here, we try to continue closing devices */
1650 }
1651 }
1652
1653 PaUtil_FreeMemory( handlesAndBuffers->waveHandles );
1654 handlesAndBuffers->waveHandles = 0;
1655 }
1656
1657 if( handlesAndBuffers->bufferEvent )
1658 {
1659 result = CloseHandleWithPaError( handlesAndBuffers->bufferEvent );
1660 handlesAndBuffers->bufferEvent = 0;
1661 }
1662
1663 return result;
1664 }
1665
1666
1667 static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
1668 unsigned long hostBufferCount,
1669 PaSampleFormat hostSampleFormat,
1670 unsigned long framesPerHostBuffer,
1671 PaWinMmeDeviceAndChannelCount *devices,
1672 int isInput )
1673 {
1674 PaError result = paNoError;
1675 MMRESULT mmresult;
1676 WAVEHDR *deviceWaveHeaders;
1677 signed int i, j;
1678
1679 /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
1680 has already been called to zero some fields */
1681
1682
1683 /* allocate an array of pointers to arrays of wave headers, one array of
1684 wave headers per device */
1685 handlesAndBuffers->waveHeaders = (WAVEHDR**)PaUtil_AllocateMemory( sizeof(WAVEHDR*) * handlesAndBuffers->deviceCount );
1686 if( !handlesAndBuffers->waveHeaders )
1687 {
1688 result = paInsufficientMemory;
1689 goto error;
1690 }
1691
1692 for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
1693 handlesAndBuffers->waveHeaders[i] = 0;
1694
1695 handlesAndBuffers->bufferCount = hostBufferCount;
1696
1697 for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
1698 {
1699 int bufferBytes = Pa_GetSampleSize( hostSampleFormat ) *
1700 framesPerHostBuffer * devices[i].channelCount;
1701 if( bufferBytes < 0 )
1702 {
1703 result = paInternalError;
1704 goto error;
1705 }
1706
1707 /* Allocate an array of wave headers for device i */
1708 deviceWaveHeaders = (WAVEHDR *) PaUtil_AllocateMemory( sizeof(WAVEHDR)*hostBufferCount );
1709 if( !deviceWaveHeaders )
1710 {
1711 result = paInsufficientMemory;
1712 goto error;
1713 }
1714
1715 for( j=0; j < (signed int)hostBufferCount; ++j )
1716 deviceWaveHeaders[j].lpData = 0;
1717
1718 handlesAndBuffers->waveHeaders[i] = deviceWaveHeaders;
1719
1720 /* Allocate a buffer for each wave header */
1721 for( j=0; j < (signed int)hostBufferCount; ++j )
1722 {
1723 deviceWaveHeaders[j].lpData = (char *)PaUtil_AllocateMemory( bufferBytes );
1724 if( !deviceWaveHeaders[j].lpData )
1725 {
1726 result = paInsufficientMemory;
1727 goto error;
1728 }
1729 deviceWaveHeaders[j].dwBufferLength = bufferBytes;
1730 deviceWaveHeaders[j].dwUser = 0xFFFFFFFF; /* indicates that *PrepareHeader() has not yet been called, for error clean up code */
1731
1732 if( isInput )
1733 {
1734 mmresult = waveInPrepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
1735 if( mmresult != MMSYSERR_NOERROR )
1736 {
1737 result = paUnanticipatedHostError;
1738 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
1739 goto error;
1740 }
1741 }
1742 else /* output */
1743 {
1744 mmresult = waveOutPrepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
1745 if( mmresult != MMSYSERR_NOERROR )
1746 {
1747 result = paUnanticipatedHostError;
1748 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
1749 goto error;
1750 }
1751 }
1752 deviceWaveHeaders[j].dwUser = devices[i].channelCount;
1753 }
1754 }
1755
1756 return result;
1757
1758 error:
1759 TerminateWaveHeaders( handlesAndBuffers, isInput );
1760
1761 return result;
1762 }
1763
1764
1765 static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput )
1766 {
1767 signed int i, j;
1768 WAVEHDR *deviceWaveHeaders;
1769
1770 if( handlesAndBuffers->waveHeaders )
1771 {
1772 for( i = handlesAndBuffers->deviceCount-1; i >= 0 ; --i )
1773 {
1774 deviceWaveHeaders = handlesAndBuffers->waveHeaders[i]; /* wave headers for device i */
1775 if( deviceWaveHeaders )
1776 {
1777 for( j = handlesAndBuffers->bufferCount-1; j >= 0; --j )
1778 {
1779 if( deviceWaveHeaders[j].lpData )
1780 {
1781 if( deviceWaveHeaders[j].dwUser != 0xFFFFFFFF )
1782 {
1783 if( isInput )
1784 waveInUnprepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
1785 else
1786 waveOutUnprepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
1787 }
1788
1789 PaUtil_FreeMemory( deviceWaveHeaders[j].lpData );
1790 }
1791 }
1792
1793 PaUtil_FreeMemory( deviceWaveHeaders );
1794 }
1795 }
1796
1797 PaUtil_FreeMemory( handlesAndBuffers->waveHeaders );
1798 handlesAndBuffers->waveHeaders = 0;
1799 }
1800 }
1801
1802
1803
1804 /* PaWinMmeStream - a stream data structure specifically for this implementation */
1805 /* note that struct PaWinMmeStream is typedeffed to PaWinMmeStream above. */
1806 struct PaWinMmeStream
1807 {
1808 PaUtilStreamRepresentation streamRepresentation;
1809 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
1810 PaUtilBufferProcessor bufferProcessor;
1811
1812 int primeStreamUsingCallback;
1813
1814 PaWinMmeSingleDirectionHandlesAndBuffers input;
1815 PaWinMmeSingleDirectionHandlesAndBuffers output;
1816
1817 /* Processing thread management -------------- */
1818 HANDLE abortEvent;
1819 HANDLE processingThread;
1820 DWORD processingThreadId;
1821
1822 char throttleProcessingThreadOnOverload; /* 0 -> don't throtte, non-0 -> throttle */
1823 int processingThreadPriority;
1824 int highThreadPriority;
1825 int throttledThreadPriority;
1826 unsigned long throttledSleepMsecs;
1827
1828 int isStopped;
1829 volatile int isActive;
1830 volatile int stopProcessing; /* stop thread once existing buffers have been returned */
1831 volatile int abortProcessing; /* stop thread immediately */
1832
1833 DWORD allBuffersDurationMs; /* used to calculate timeouts */
1834 };
1835
1836 /* updates deviceCount if PaWinMmeUseMultipleDevices is used */
1837
1838 static PaError ValidateWinMmeSpecificStreamInfo(
1839 const PaStreamParameters *streamParameters,
1840 const PaWinMmeStreamInfo *streamInfo,
1841 char *throttleProcessingThreadOnOverload,
1842 unsigned long *deviceCount )
1843 {
1844 if( streamInfo )
1845 {
1846 if( streamInfo->size != sizeof( PaWinMmeStreamInfo )
1847 || streamInfo->version != 1 )
1848 {
1849 return paIncompatibleHostApiSpecificStreamInfo;
1850 }
1851
1852 if( streamInfo->flags & paWinMmeDontThrottleOverloadedProcessingThread )
1853 *throttleProcessingThreadOnOverload = 0;
1854
1855 if( streamInfo->flags & paWinMmeUseMultipleDevices )
1856 {
1857 if( streamParameters->device != paUseHostApiSpecificDeviceSpecification )
1858 return paInvalidDevice;
1859
1860 *deviceCount = streamInfo->deviceCount;
1861 }
1862 }
1863
1864 return paNoError;
1865 }
1866
1867 static PaError RetrieveDevicesFromStreamParameters(
1868 struct PaUtilHostApiRepresentation *hostApi,
1869 const PaStreamParameters *streamParameters,
1870 const PaWinMmeStreamInfo *streamInfo,
1871 PaWinMmeDeviceAndChannelCount *devices,
1872 unsigned long deviceCount )
1873 {
1874 PaError result = paNoError;
1875 unsigned int i;
1876 int totalChannelCount;
1877 PaDeviceIndex hostApiDevice;
1878
1879 if( streamInfo && streamInfo->flags & paWinMmeUseMultipleDevices )
1880 {
1881 totalChannelCount = 0;
1882 for( i=0; i < deviceCount; ++i )
1883 {
1884 /* validate that the device number is within range */
1885 result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice,
1886 streamInfo->devices[i].device, hostApi );
1887 if( result != paNoError )
1888 return result;
1889
1890 devices[i].device = hostApiDevice;
1891 devices[i].channelCount = streamInfo->devices[i].channelCount;
1892
1893 totalChannelCount += devices[i].channelCount;
1894 }
1895
1896 if( totalChannelCount != streamParameters->channelCount )
1897 {
1898 /* channelCount must match total channels specified by multiple devices */
1899 return paInvalidChannelCount; /* REVIEW use of this error code */
1900 }
1901 }
1902 else
1903 {
1904 devices[0].device = streamParameters->device;
1905 devices[0].channelCount = streamParameters->channelCount;
1906 }
1907
1908 return result;
1909 }
1910
1911 static PaError ValidateInputChannelCounts(
1912 struct PaUtilHostApiRepresentation *hostApi,
1913 PaWinMmeDeviceAndChannelCount *devices,
1914 unsigned long deviceCount )
1915 {
1916 unsigned int i;
1917
1918 for( i=0; i < deviceCount; ++i )
1919 {
1920 if( devices[i].channelCount < 1 || devices[i].channelCount
1921 > hostApi->deviceInfos[ devices[i].device ]->maxInputChannels )
1922 return paInvalidChannelCount;
1923 }
1924
1925 return paNoError;
1926 }
1927
1928 static PaError ValidateOutputChannelCounts(
1929 struct PaUtilHostApiRepresentation *hostApi,
1930 PaWinMmeDeviceAndChannelCount *devices,
1931 unsigned long deviceCount )
1932 {
1933 unsigned int i;
1934
1935 for( i=0; i < deviceCount; ++i )
1936 {
1937 if( devices[i].channelCount < 1 || devices[i].channelCount
1938 > hostApi->deviceInfos[ devices[i].device ]->maxOutputChannels )
1939 return paInvalidChannelCount;
1940 }
1941
1942 return paNoError;
1943 }
1944
1945
1946 /* the following macros are intended to improve the readability of the following code */
1947 #define PA_IS_INPUT_STREAM_( stream ) ( stream ->input.waveHandles )
1948 #define PA_IS_OUTPUT_STREAM_( stream ) ( stream ->output.waveHandles )
1949 #define PA_IS_FULL_DUPLEX_STREAM_( stream ) ( stream ->input.waveHandles && stream ->output.waveHandles )
1950 #define PA_IS_HALF_DUPLEX_STREAM_( stream ) ( !(stream ->input.waveHandles && stream ->output.waveHandles) )
1951
1952 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
1953 PaStream** s,
1954 const PaStreamParameters *inputParameters,
1955 const PaStreamParameters *outputParameters,
1956 double sampleRate,
1957 unsigned long framesPerBuffer,
1958 PaStreamFlags streamFlags,
1959 PaStreamCallback *streamCallback,
1960 void *userData )
1961 {
1962 PaError result;
1963 PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
1964 PaWinMmeStream *stream = 0;
1965 int bufferProcessorIsInitialized = 0;
1966 int streamRepresentationIsInitialized = 0;
1967 PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
1968 int inputChannelCount, outputChannelCount;
1969 PaSampleFormat inputSampleFormat, outputSampleFormat;
1970 double suggestedInputLatency, suggestedOutputLatency;
1971 PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
1972 unsigned long framesPerHostInputBuffer;
1973 unsigned long hostInputBufferCount;
1974 unsigned long framesPerHostOutputBuffer;
1975 unsigned long hostOutputBufferCount;
1976 unsigned long framesPerBufferProcessorCall;
1977 PaWinMmeDeviceAndChannelCount *inputDevices = 0; /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
1978 unsigned long inputDeviceCount = 0;
1979 PaWinMmeDeviceAndChannelCount *outputDevices = 0;
1980 unsigned long outputDeviceCount = 0; /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
1981 char throttleProcessingThreadOnOverload = 1;
1982
1983
1984 if( inputParameters )
1985 {
1986 inputChannelCount = inputParameters->channelCount;
1987 inputSampleFormat = inputParameters->sampleFormat;
1988 suggestedInputLatency = inputParameters->suggestedLatency;
1989
1990 inputDeviceCount = 1;
1991
1992 /* validate input hostApiSpecificStreamInfo */
1993 inputStreamInfo = (PaWinMmeStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
1994 result = ValidateWinMmeSpecificStreamInfo( inputParameters, inputStreamInfo,
1995 &throttleProcessingThreadOnOverload,
1996 &inputDeviceCount );
1997 if( result != paNoError ) return result;
1998
1999 inputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * inputDeviceCount );
2000 if( !inputDevices ) return paInsufficientMemory;
2001
2002 result = RetrieveDevicesFromStreamParameters( hostApi, inputParameters, inputStreamInfo, inputDevices, inputDeviceCount );
2003 if( result != paNoError ) return result;
2004
2005 result = ValidateInputChannelCounts( hostApi, inputDevices, inputDeviceCount );
2006 if( result != paNoError ) return result;
2007
2008 hostInputSampleFormat =
2009 PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );
2010 }
2011 else
2012 {
2013 inputChannelCount = 0;
2014 inputSampleFormat = 0;
2015 suggestedInputLatency = 0.;
2016 inputStreamInfo = 0;
2017 hostInputSampleFormat = 0;
2018 }
2019
2020
2021 if( outputParameters )
2022 {
2023 outputChannelCount = outputParameters->channelCount;
2024 outputSampleFormat = outputParameters->sampleFormat;
2025 suggestedOutputLatency = outputParameters->suggestedLatency;
2026
2027 outputDeviceCount = 1;
2028
2029 /* validate output hostApiSpecificStreamInfo */
2030 outputStreamInfo = (PaWinMmeStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
2031 result = ValidateWinMmeSpecificStreamInfo( outputParameters, outputStreamInfo,
2032 &throttleProcessingThreadOnOverload,
2033 &outputDeviceCount );
2034 if( result != paNoError ) return result;
2035
2036 outputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * outputDeviceCount );
2037 if( !outputDevices ) return paInsufficientMemory;
2038
2039 result = RetrieveDevicesFromStreamParameters( hostApi, outputParameters, outputStreamInfo, outputDevices, outputDeviceCount );
2040 if( result != paNoError ) return result;
2041
2042 result = ValidateOutputChannelCounts( hostApi, outputDevices, outputDeviceCount );
2043 if( result != paNoError ) return result;
2044
2045 hostOutputSampleFormat =
2046 PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );
2047 }
2048 else
2049 {
2050 outputChannelCount = 0;
2051 outputSampleFormat = 0;
2052 outputStreamInfo = 0;
2053 hostOutputSampleFormat = 0;
2054 suggestedOutputLatency = 0.;
2055 }
2056
2057
2058 /*
2059 IMPLEMENT ME:
2060 - alter sampleRate to a close allowable rate if possible / necessary
2061 */
2062
2063
2064 /* validate platform specific flags */
2065 if( (streamFlags & paPlatformSpecificFlags) != 0 )
2066 return paInvalidFlag; /* unexpected platform specific flag */
2067
2068
2069 result = CalculateBufferSettings( &framesPerHostInputBuffer, &hostInputBufferCount,
2070 &framesPerHostOutputBuffer, &hostOutputBufferCount,
2071 inputChannelCount, hostInputSampleFormat, suggestedInputLatency, inputStreamInfo,
2072 outputChannelCount, hostOutputSampleFormat, suggestedOutputLatency, outputStreamInfo,
2073 sampleRate, framesPerBuffer );
2074 if( result != paNoError ) goto error;
2075
2076
2077 stream = (PaWinMmeStream*)PaUtil_AllocateMemory( sizeof(PaWinMmeStream) );
2078 if( !stream )
2079 {
2080 result = paInsufficientMemory;
2081 goto error;
2082 }
2083
2084 InitializeSingleDirectionHandlesAndBuffers( &stream->input );
2085 InitializeSingleDirectionHandlesAndBuffers( &stream->output );
2086
2087 stream->abortEvent = 0;
2088 stream->processingThread = 0;
2089
2090 stream->throttleProcessingThreadOnOverload = throttleProcessingThreadOnOverload;
2091
2092 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
2093 ( (streamCallback)
2094 ? &winMmeHostApi->callbackStreamInterface
2095 : &winMmeHostApi->blockingStreamInterface ),
2096 streamCallback, userData );
2097 streamRepresentationIsInitialized = 1;
2098
2099 PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
2100
2101
2102 if( inputParameters && outputParameters ) /* full duplex */
2103 {
2104 if( framesPerHostInputBuffer < framesPerHostOutputBuffer )
2105 {
2106 assert( (framesPerHostOutputBuffer % framesPerHostInputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */
2107
2108 framesPerBufferProcessorCall = framesPerHostInputBuffer;
2109 }
2110 else
2111 {
2112 assert( (framesPerHostInputBuffer % framesPerHostOutputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */
2113
2114 framesPerBufferProcessorCall = framesPerHostOutputBuffer;
2115 }
2116 }
2117 else if( inputParameters )
2118 {
2119 framesPerBufferProcessorCall = framesPerHostInputBuffer;
2120 }
2121 else if( outputParameters )
2122 {
2123 framesPerBufferProcessorCall = framesPerHostOutputBuffer;
2124 }
2125
2126 stream->input.framesPerBuffer = framesPerHostInputBuffer;
2127 stream->output.framesPerBuffer = framesPerHostOutputBuffer;
2128
2129 result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
2130 inputChannelCount, inputSampleFormat, hostInputSampleFormat,
2131 outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
2132 sampleRate, streamFlags, framesPerBuffer,
2133 framesPerBufferProcessorCall, paUtilFixedHostBufferSize,
2134 streamCallback, userData );
2135 if( result != paNoError ) goto error;
2136
2137 bufferProcessorIsInitialized = 1;
2138
2139 stream->streamRepresentation.streamInfo.inputLatency =
2140 (double)(PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)
2141 +(framesPerHostInputBuffer * (hostInputBufferCount-1))) / sampleRate;
2142 stream->streamRepresentation.streamInfo.outputLatency =
2143 (double)(PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)
2144 +(framesPerHostOutputBuffer * (hostOutputBufferCount-1))) / sampleRate;
2145 stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
2146
2147 stream->primeStreamUsingCallback = ( (streamFlags&paPrimeOutputBuffersUsingStreamCallback) && streamCallback ) ? 1 : 0;
2148
2149 /* time to sleep when throttling due to >100% cpu usage.
2150 -a quater of a buffer's duration */
2151 stream->throttledSleepMsecs =
2152 (unsigned long)(stream->bufferProcessor.framesPerHostBuffer *
2153 stream->bufferProcessor.samplePeriod * .25 * 1000);
2154
2155 stream->isStopped = 1;
2156 stream->isActive = 0;
2157
2158
2159 /* for maximum compatibility with multi-device multichannel drivers,
2160 we first open all devices, then we prepare all buffers, finally
2161 we start all devices ( in StartStream() ). teardown in reverse order.
2162 */
2163
2164 if( inputParameters )
2165 {
2166 result = InitializeWaveHandles( winMmeHostApi, &stream->input,
2167 stream->bufferProcessor.bytesPerHostInputSample, sampleRate,
2168 inputDevices, inputDeviceCount, 1 /* isInput */ );
2169 if( result != paNoError ) goto error;
2170 }
2171
2172 if( outputParameters )
2173 {
2174 result = InitializeWaveHandles( winMmeHostApi, &stream->output,
2175 stream->bufferProcessor.bytesPerHostOutputSample, sampleRate,
2176 outputDevices, outputDeviceCount, 0 /* isInput */ );
2177 if( result != paNoError ) goto error;
2178 }
2179
2180 if( inputParameters )
2181 {
2182 result = InitializeWaveHeaders( &stream->input, hostInputBufferCount,
2183 hostInputSampleFormat, framesPerHostInputBuffer, inputDevices, 1 /* isInput */ );
2184 if( result != paNoError ) goto error;
2185 }
2186
2187 if( outputParameters )
2188 {
2189 result = InitializeWaveHeaders( &stream->output, hostOutputBufferCount,
2190 hostOutputSampleFormat, framesPerHostOutputBuffer, outputDevices, 0 /* not isInput */ );
2191 if( result != paNoError ) goto error;
2192
2193 stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostOutputBuffer * stream->output.bufferCount) / sampleRate);
2194 }
2195 else
2196 {
2197 stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostInputBuffer * stream->input.bufferCount) / sampleRate);
2198 }
2199
2200
2201 if( streamCallback )
2202 {
2203 /* abort event is only needed for callback streams */
2204 result = CreateEventWithPaError( &stream->abortEvent, NULL, TRUE, FALSE, NULL );
2205 if( result != paNoError ) goto error;
2206 }
2207
2208 *s = (PaStream*)stream;
2209
2210 return result;
2211
2212 error:
2213
2214 if( stream )
2215 {
2216 if( stream->abortEvent )
2217 CloseHandle( stream->abortEvent );
2218
2219 TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
2220 TerminateWaveHeaders( &stream->input, 1 /* isInput */ );
2221
2222 TerminateWaveHandles( &stream->output, 0 /* not isInput */, 1 /* currentlyProcessingAnError */ );
2223 TerminateWaveHandles( &stream->input, 1 /* isInput */, 1 /* currentlyProcessingAnError */ );
2224
2225 if( bufferProcessorIsInitialized )
2226 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
2227
2228 if( streamRepresentationIsInitialized )
2229 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
2230
2231 PaUtil_FreeMemory( stream );
2232 }
2233
2234 return result;
2235 }
2236
2237
2238 /* return non-zero if all current buffers are done */
2239 static int BuffersAreDone( WAVEHDR **waveHeaders, unsigned int deviceCount, int bufferIndex )
2240 {
2241 unsigned int i;
2242
2243 for( i=0; i < deviceCount; ++i )
2244 {
2245 if( !(waveHeaders[i][ bufferIndex ].dwFlags & WHDR_DONE) )
2246 {
2247 return 0;
2248 }
2249 }
2250
2251 return 1;
2252 }
2253
2254 static int CurrentInputBuffersAreDone( PaWinMmeStream *stream )
2255 {
2256 return BuffersAreDone( stream->input.waveHeaders, stream->input.deviceCount, stream->input.currentBufferIndex );
2257 }
2258
2259 static int CurrentOutputBuffersAreDone( PaWinMmeStream *stream )
2260 {
2261 return BuffersAreDone( stream->output.waveHeaders, stream->output.deviceCount, stream->output.currentBufferIndex );
2262 }
2263
2264
2265 /* return non-zero if any buffers are queued */
2266 static int NoBuffersAreQueued( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
2267 {
2268 unsigned int i, j;
2269
2270 if( handlesAndBuffers->waveHandles )
2271 {
2272 for( i=0; i < handlesAndBuffers->bufferCount; ++i )
2273 {
2274 for( j=0; j < handlesAndBuffers->deviceCount; ++j )
2275 {
2276 if( !( handlesAndBuffers->waveHeaders[ j ][ i ].dwFlags & WHDR_DONE) )
2277 {
2278 return 0;
2279 }
2280 }
2281 }
2282 }
2283
2284 return 1;
2285 }
2286
2287
2288 #define PA_CIRCULAR_INCREMENT_( current, max )\
2289 ( (((current) + 1) >= (max)) ? (0) : (current+1) )
2290
2291 #define PA_CIRCULAR_DECREMENT_( current, max )\
2292 ( ((current) == 0) ? ((max)-1) : (current-1) )
2293
2294
2295 static signed long GetAvailableFrames( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
2296 {
2297 signed long result = 0;
2298 unsigned int i;
2299
2300 if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, handlesAndBuffers->currentBufferIndex ) )
2301 {
2302 /* we could calculate the following in O(1) if we kept track of the
2303 last done buffer */
2304 result = handlesAndBuffers->framesPerBuffer - handlesAndBuffers->framesUsedInCurrentBuffer;
2305
2306 i = PA_CIRCULAR_INCREMENT_( handlesAndBuffers->currentBufferIndex, handlesAndBuffers->bufferCount );
2307 while( i != handlesAndBuffers->currentBufferIndex )
2308 {
2309 if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, i ) )
2310 {
2311 result += handlesAndBuffers->framesPerBuffer;
2312 i = PA_CIRCULAR_INCREMENT_( i, handlesAndBuffers->bufferCount );
2313 }
2314 else
2315 break;
2316 }
2317 }
2318
2319 return result;
2320 }
2321
2322
2323 static PaError AdvanceToNextInputBuffer( PaWinMmeStream *stream )
2324 {
2325 PaError result = paNoError;
2326 MMRESULT mmresult;
2327 unsigned int i;
2328
2329 for( i=0; i < stream->input.deviceCount; ++i )
2330 {
2331 mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[i],
2332 &stream->input.waveHeaders[i][ stream->input.currentBufferIndex ],
2333 sizeof(WAVEHDR) );
2334 if( mmresult != MMSYSERR_NOERROR )
2335 {
2336 result = paUnanticipatedHostError;
2337 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
2338 }
2339 }
2340
2341 stream->input.currentBufferIndex =
2342 PA_CIRCULAR_INCREMENT_( stream->input.currentBufferIndex, stream->input.bufferCount );
2343
2344 stream->input.framesUsedInCurrentBuffer = 0;
2345
2346 return result;
2347 }
2348
2349
2350 static PaError AdvanceToNextOutputBuffer( PaWinMmeStream *stream )
2351 {
2352 PaError result = paNoError;
2353 MMRESULT mmresult;
2354 unsigned int i;
2355
2356 for( i=0; i < stream->output.deviceCount; ++i )
2357 {
2358 mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[i],
2359 &stream->output.waveHeaders[i][ stream->output.currentBufferIndex ],
2360 sizeof(WAVEHDR) );
2361 if( mmresult != MMSYSERR_NOERROR )
2362 {
2363 result = paUnanticipatedHostError;
2364 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
2365 }
2366 }
2367
2368 stream->output.currentBufferIndex =
2369 PA_CIRCULAR_INCREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );
2370
2371 stream->output.framesUsedInCurrentBuffer = 0;
2372
2373 return result;
2374 }
2375
2376
2377 /* requeue all but the most recent input with the driver. Used for catching
2378 up after a total input buffer underrun */
2379 static PaError CatchUpInputBuffers( PaWinMmeStream *stream )
2380 {
2381 PaError result = paNoError;
2382 unsigned int i;
2383
2384 for( i=0; i < stream->input.bufferCount - 1; ++i )
2385 {
2386 result = AdvanceToNextInputBuffer( stream );
2387 if( result != paNoError )
2388 break;
2389 }
2390
2391 return result;
2392 }
2393
2394
2395 /* take the most recent output and duplicate it to all other output buffers
2396 and requeue them. Used for catching up after a total output buffer underrun.
2397 */
2398 static PaError CatchUpOutputBuffers( PaWinMmeStream *stream )
2399 {
2400 PaError result = paNoError;
2401 unsigned int i, j;
2402 unsigned int previousBufferIndex =
2403 PA_CIRCULAR_DECREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );
2404
2405 for( i=0; i < stream->output.bufferCount - 1; ++i )
2406 {
2407 for( j=0; j < stream->output.deviceCount; ++j )
2408 {
2409 if( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData
2410 != stream->output.waveHeaders[j][ previousBufferIndex ].lpData )
2411 {
2412 CopyMemory( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData,
2413 stream->output.waveHeaders[j][ previousBufferIndex ].lpData,
2414 stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].dwBufferLength );
2415 }
2416 }
2417
2418 result = AdvanceToNextOutputBuffer( stream );
2419 if( result != paNoError )
2420 break;
2421 }
2422
2423 return result;
2424 }
2425
2426
2427 static DWORD WINAPI ProcessingThreadProc( void *pArg )
2428 {
2429 PaWinMmeStream *stream = (PaWinMmeStream *)pArg;
2430 HANDLE events[3];
2431 int eventCount = 0;
2432 DWORD result = paNoError;
2433 DWORD waitResult;
2434 DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
2435 int hostBuffersAvailable;
2436 signed int hostInputBufferIndex, hostOutputBufferIndex;
2437 PaStreamCallbackFlags statusFlags;
2438 int callbackResult;
2439 int done = 0;
2440 unsigned int channel, i;
2441 unsigned long framesProcessed;
2442
2443 /* prepare event array for call to WaitForMultipleObjects() */
2444 if( stream->input.bufferEvent )
2445 events[eventCount++] = stream->input.bufferEvent;
2446 if( stream->output.bufferEvent )
2447 events[eventCount++] = stream->output.bufferEvent;
2448 events[eventCount++] = stream->abortEvent;
2449
2450 statusFlags = 0; /** @todo support paInputUnderflow, paOutputOverflow and paNeverDropInput */
2451
2452 /* loop until something causes us to stop */
2453 do{
2454 /* wait for MME to signal that a buffer is available, or for
2455 the PA abort event to be signaled.
2456
2457 When this indicates that one or more buffers are available
2458 NoBuffersAreQueued() and Current*BuffersAreDone are used below to
2459 poll for additional done buffers. NoBuffersAreQueued() will fail
2460 to identify an underrun/overflow if the driver doesn't mark all done
2461 buffers prior to signalling the event. Some drivers do this
2462 (eg RME Digi96, and others don't eg VIA PC 97 input). This isn't a
2463 huge problem, it just means that we won't always be able to detect
2464 underflow/overflow.
2465 */
2466 waitResult = WaitForMultipleObjects( eventCount, events, FALSE /* wait all = FALSE */, timeout );
2467 if( waitResult == WAIT_FAILED )
2468 {
2469 result = paUnanticipatedHostError;
2470 /** @todo FIXME/REVIEW: can't return host error info from an asyncronous thread */
2471 done = 1;
2472 }
2473 else if( waitResult == WAIT_TIMEOUT )
2474 {
2475 /* if a timeout is encountered, continue */
2476 }
2477
2478 if( stream->abortProcessing )
2479 {
2480 /* Pa_AbortStream() has been called, stop processing immediately */
2481 done = 1;
2482 }
2483 else if( stream->stopProcessing )
2484 {
2485 /* Pa_StopStream() has been called or the user callback returned
2486 non-zero, processing will continue until all output buffers
2487 are marked as done. The stream will stop immediately if it
2488 is input-only.
2489 */
2490
2491 if( PA_IS_OUTPUT_STREAM_(stream) )
2492 {
2493 if( NoBuffersAreQueued( &stream->output ) )
2494 done = 1; /* Will cause thread to return. */
2495 }
2496 else
2497 {
2498 /* input only stream */
2499 done = 1; /* Will cause thread to return. */
2500 }
2501 }
2502 else
2503 {
2504 hostBuffersAvailable = 1;
2505
2506 /* process all available host buffers */
2507 do
2508 {
2509 hostInputBufferIndex = -1;
2510 hostOutputBufferIndex = -1;
2511
2512 if( PA_IS_INPUT_STREAM_(stream) )
2513 {
2514 if( CurrentInputBuffersAreDone( stream ) )
2515 {
2516 if( NoBuffersAreQueued( &stream->input ) )
2517 {
2518 /** @todo
2519 if all of the other buffers are also ready then
2520 we discard all but the most recent. This is an
2521 input buffer overflow. FIXME: these buffers should
2522 be passed to the callback in a paNeverDropInput
2523 stream.
2524
2525 note that it is also possible for an input overflow
2526 to happen while the callback is processing a buffer.
2527 that is handled further down.
2528 */
2529 result = CatchUpInputBuffers( stream );
2530 if( result != paNoError )
2531 done = 1;
2532
2533 statusFlags |= paInputOverflow;
2534 }
2535
2536 hostInputBufferIndex = stream->input.currentBufferIndex;
2537 }
2538 }
2539
2540 if( PA_IS_OUTPUT_STREAM_(stream) )
2541 {
2542 if( CurrentOutputBuffersAreDone( stream ) )
2543 {
2544 /* ok, we have an output buffer */
2545
2546 if( NoBuffersAreQueued( &stream->output ) )
2547 {
2548 /*
2549 if all of the other buffers are also ready, catch up by copying
2550 the most recently generated buffer into all but one of the output
2551 buffers.
2552
2553 note that this catch up code only handles the case where all
2554 buffers have been played out due to this thread not having
2555 woken up at all. a more common case occurs when this thread
2556 is woken up, processes one buffer, but takes too long, and as
2557 a result all the other buffers have become un-queued. that
2558 case is handled further down.
2559 */
2560
2561 result = CatchUpOutputBuffers( stream );
2562 if( result != paNoError )
2563 done = 1;
2564
2565 statusFlags |= paOutputUnderflow;
2566 }
2567
2568 hostOutputBufferIndex = stream->output.currentBufferIndex;
2569 }
2570 }
2571
2572
2573 if( (PA_IS_FULL_DUPLEX_STREAM_(stream) && hostInputBufferIndex != -1 && hostOutputBufferIndex != -1) ||
2574 (PA_IS_HALF_DUPLEX_STREAM_(stream) && ( hostInputBufferIndex != -1 || hostOutputBufferIndex != -1 ) ) )
2575 {
2576 PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */
2577
2578
2579 if( PA_IS_OUTPUT_STREAM_(stream) )
2580 {
2581 /* set timeInfo.currentTime and calculate timeInfo.outputBufferDacTime
2582 from the current wave out position */
2583 MMTIME mmtime;
2584 double timeBeforeGetPosition, timeAfterGetPosition;
2585 double time;
2586 long framesInBufferRing;
2587 long writePosition;
2588 long playbackPosition;
2589 HWAVEOUT firstWaveOutDevice = ((HWAVEOUT*)stream->output.waveHandles)[0];
2590
2591 mmtime.wType = TIME_SAMPLES;
2592 timeBeforeGetPosition = PaUtil_GetTime();
2593 waveOutGetPosition( firstWaveOutDevice, &mmtime, sizeof(MMTIME) );
2594 timeAfterGetPosition = PaUtil_GetTime();
2595
2596 timeInfo.currentTime = timeAfterGetPosition;
2597
2598 /* approximate time at which wave out position was measured
2599 as half way between timeBeforeGetPosition and timeAfterGetPosition */
2600 time = timeBeforeGetPosition + (timeAfterGetPosition - timeBeforeGetPosition) * .5;
2601
2602 framesInBufferRing = stream->output.bufferCount * stream->bufferProcessor.framesPerHostBuffer;
2603 playbackPosition = mmtime.u.sample % framesInBufferRing;
2604
2605 writePosition = stream->output.currentBufferIndex * stream->bufferProcessor.framesPerHostBuffer
2606 + stream->output.framesUsedInCurrentBuffer;
2607
2608 if( playbackPosition >= writePosition ){
2609 timeInfo.outputBufferDacTime =
2610 time + ((double)( writePosition + (framesInBufferRing - playbackPosition) ) * stream->bufferProcessor.samplePeriod );
2611 }else{
2612 timeInfo.outputBufferDacTime =
2613 time + ((double)( writePosition - playbackPosition ) * stream->bufferProcessor.samplePeriod );
2614 }
2615 }
2616
2617
2618 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
2619
2620 PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, statusFlags );
2621
2622 /* reset status flags once they have been passed to the buffer processor */
2623 statusFlags = 0;
2624
2625 if( PA_IS_INPUT_STREAM_(stream) )
2626 {
2627 PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
2628
2629 channel = 0;
2630 for( i=0; i<stream->input.deviceCount; ++i )
2631 {
2632 /* we have stored the number of channels in the buffer in dwUser */
2633 int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
2634
2635 PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
2636 stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
2637 stream->input.framesUsedInCurrentBuffer * channelCount *
2638 stream->bufferProcessor.bytesPerHostInputSample,
2639 channelCount );
2640
2641
2642 channel += channelCount;
2643 }
2644 }
2645
2646 if( PA_IS_OUTPUT_STREAM_(stream) )
2647 {
2648 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
2649
2650 channel = 0;
2651 for( i=0; i<stream->output.deviceCount; ++i )
2652 {
2653 /* we have stored the number of channels in the buffer in dwUser */
2654 int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
2655
2656 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
2657 stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
2658 stream->output.framesUsedInCurrentBuffer * channelCount *
2659 stream->bufferProcessor.bytesPerHostOutputSample,
2660 channelCount );
2661
2662 channel += channelCount;
2663 }
2664 }
2665
2666 callbackResult = paContinue;
2667 framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
2668
2669 stream->input.framesUsedInCurrentBuffer += framesProcessed;
2670 stream->output.framesUsedInCurrentBuffer += framesProcessed;
2671
2672 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
2673
2674 if( callbackResult == paContinue )
2675 {
2676 /* nothing special to do */
2677 }
2678 else if( callbackResult == paAbort )
2679 {
2680 stream->abortProcessing = 1;
2681 done = 1;
2682 /** @todo FIXME: should probably reset the output device immediately once the callback returns paAbort */
2683 result = paNoError;
2684 }
2685 else
2686 {
2687 /* User callback has asked us to stop with paComplete or other non-zero value */
2688 stream->stopProcessing = 1; /* stop once currently queued audio has finished */
2689 result = paNoError;
2690 }
2691
2692
2693 if( PA_IS_INPUT_STREAM_(stream)
2694 && stream->stopProcessing == 0 && stream->abortProcessing == 0
2695 && stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
2696 {
2697 if( NoBuffersAreQueued( &stream->input ) )
2698 {
2699 /** @todo need to handle PaNeverDropInput here where necessary */
2700 result = CatchUpInputBuffers( stream );
2701 if( result != paNoError )
2702 done = 1;
2703
2704 statusFlags |= paInputOverflow;
2705 }
2706
2707 result = AdvanceToNextInputBuffer( stream );
2708 if( result != paNoError )
2709 done = 1;
2710 }
2711
2712
2713 if( PA_IS_OUTPUT_STREAM_(stream) && !stream->abortProcessing )
2714 {
2715 if( stream->stopProcessing &&
2716 stream->output.framesUsedInCurrentBuffer < stream->output.framesPerBuffer )
2717 {
2718 /* zero remaining samples in output output buffer and flush */
2719
2720 stream->output.framesUsedInCurrentBuffer += PaUtil_ZeroOutput( &stream->bufferProcessor,
2721 stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
2722
2723 /* we send the entire buffer to the output devices, but we could
2724 just send a partial buffer, rather than zeroing the unused
2725 samples.
2726 */
2727 }
2728
2729 if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
2730 {
2731 /* check for underflow before enquing the just-generated buffer,
2732 but recover from underflow after enquing it. This ensures
2733 that the most recent audio segment is repeated */
2734 int outputUnderflow = NoBuffersAreQueued( &stream->output );
2735
2736 result = AdvanceToNextOutputBuffer( stream );
2737 if( result != paNoError )
2738 done = 1;
2739
2740 if( outputUnderflow && !done && !stream->stopProcessing )
2741 {
2742 /* Recover from underflow in the case where the
2743 underflow occured while processing the buffer
2744 we just finished */
2745
2746 result = CatchUpOutputBuffers( stream );
2747 if( result != paNoError )
2748 done = 1;
2749
2750 statusFlags |= paOutputUnderflow;
2751 }
2752 }
2753 }
2754
2755 if( stream->throttleProcessingThreadOnOverload != 0 )
2756 {
2757 if( stream->stopProcessing || stream->abortProcessing )
2758 {
2759 if( stream->processingThreadPriority != stream->highThreadPriority )
2760 {
2761 SetThreadPriority( stream->processingThread, stream->highThreadPriority );
2762 stream->processingThreadPriority = stream->highThreadPriority;
2763 }
2764 }
2765 else if( PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) > 1. )
2766 {
2767 if( stream->processingThreadPriority != stream->throttledThreadPriority )
2768 {
2769 SetThreadPriority( stream->processingThread, stream->throttledThreadPriority );
2770 stream->processingThreadPriority = stream->throttledThreadPriority;
2771 }
2772
2773 /* sleep to give other processes a go */
2774 Sleep( stream->throttledSleepMsecs );
2775 }
2776 else
2777 {
2778 if( stream->processingThreadPriority != stream->highThreadPriority )
2779 {
2780 SetThreadPriority( stream->processingThread, stream->highThreadPriority );
2781 stream->processingThreadPriority = stream->highThreadPriority;
2782 }
2783 }
2784 }
2785 }
2786 else
2787 {
2788 hostBuffersAvailable = 0;
2789 }
2790 }
2791 while( hostBuffersAvailable &&
2792 stream->stopProcessing == 0 &&
2793 stream->abortProcessing == 0 &&
2794 !done );
2795 }
2796 }
2797 while( !done );
2798
2799 stream->isActive = 0;
2800
2801 if( stream->streamRepresentation.streamFinishedCallback != 0 )
2802 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
2803
2804 PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
2805
2806 return result;
2807 }
2808
2809
2810 /*
2811 When CloseStream() is called, the multi-api layer ensures that
2812 the stream has already been stopped or aborted.
2813 */
2814 static PaError CloseStream( PaStream* s )
2815 {
2816 PaError result;
2817 PaWinMmeStream *stream = (PaWinMmeStream*)s;
2818
2819 result = CloseHandleWithPaError( stream->abortEvent );
2820 if( result != paNoError ) goto error;
2821
2822 TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
2823 TerminateWaveHeaders( &stream->input, 1 /* isInput */ );
2824
2825 TerminateWaveHandles( &stream->output, 0 /* not isInput */, 0 /* not currentlyProcessingAnError */ );
2826 TerminateWaveHandles( &stream->input, 1 /* isInput */, 0 /* not currentlyProcessingAnError */ );
2827
2828 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
2829 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
2830 PaUtil_FreeMemory( stream );
2831
2832 error:
2833 /** @todo REVIEW: what is the best way to clean up a stream if an error is detected? */
2834 return result;
2835 }
2836
2837
2838 static PaError StartStream( PaStream *s )
2839 {
2840 PaError result;
2841 PaWinMmeStream *stream = (PaWinMmeStream*)s;
2842 MMRESULT mmresult;
2843 unsigned int i, j;
2844 int callbackResult;
2845 unsigned int channel;
2846 unsigned long framesProcessed;
2847 PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement this for stream priming */
2848
2849 PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
2850
2851 if( PA_IS_INPUT_STREAM_(stream) )
2852 {
2853 for( i=0; i<stream->input.bufferCount; ++i )
2854 {
2855 for( j=0; j<stream->input.deviceCount; ++j )
2856 {
2857 mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[j], &stream->input.waveHeaders[j][i], sizeof(WAVEHDR) );
2858 if( mmresult != MMSYSERR_NOERROR )
2859 {
2860 result = paUnanticipatedHostError;
2861 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
2862 goto error;
2863 }
2864 }
2865 }
2866 stream->input.currentBufferIndex = 0;
2867 stream->input.framesUsedInCurrentBuffer = 0;
2868 }
2869
2870 if( PA_IS_OUTPUT_STREAM_(stream) )
2871 {
2872 for( i=0; i<stream->output.deviceCount; ++i )
2873 {
2874 if( (mmresult = waveOutPause( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
2875 {
2876 result = paUnanticipatedHostError;
2877 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
2878 goto error;
2879 }
2880 }
2881
2882 for( i=0; i<stream->output.bufferCount; ++i )
2883 {
2884 if( stream->primeStreamUsingCallback )
2885 {
2886
2887 stream->output.framesUsedInCurrentBuffer = 0;
2888 do{
2889
2890 PaUtil_BeginBufferProcessing( &stream->bufferProcessor,
2891 &timeInfo,
2892 paPrimingOutput | ((stream->input.bufferCount > 0 ) ? paInputUnderflow : 0));
2893
2894 if( stream->input.bufferCount > 0 )
2895 PaUtil_SetNoInput( &stream->bufferProcessor );
2896
2897 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
2898
2899 channel = 0;
2900 for( j=0; j<stream->output.deviceCount; ++j )
2901 {
2902 /* we have stored the number of channels in the buffer in dwUser */
2903 int channelCount = stream->output.waveHeaders[j][i].dwUser;
2904
2905 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
2906 stream->output.waveHeaders[j][i].lpData +
2907 stream->output.framesUsedInCurrentBuffer * channelCount *
2908 stream->bufferProcessor.bytesPerHostOutputSample,
2909 channelCount );
2910
2911 /* we have stored the number of channels in the buffer in dwUser */
2912 channel += channelCount;
2913 }
2914
2915 callbackResult = paContinue;
2916 framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
2917 stream->output.framesUsedInCurrentBuffer += framesProcessed;
2918
2919 if( callbackResult != paContinue )
2920 {
2921 /** @todo fix this, what do we do if callback result is non-zero during stream
2922 priming?
2923
2924 for complete: play out primed waveHeaders as usual
2925 for abort: clean up immediately.
2926 */
2927 }
2928
2929 }while( stream->output.framesUsedInCurrentBuffer != stream->output.framesPerBuffer );
2930
2931 }
2932 else
2933 {
2934 for( j=0; j<stream->output.deviceCount; ++j )
2935 {
2936 ZeroMemory( stream->output.waveHeaders[j][i].lpData, stream->output.waveHeaders[j][i].dwBufferLength );
2937 }
2938 }
2939
2940 /* we queue all channels of a single buffer frame (accross all
2941 devices, because some multidevice multichannel drivers work
2942 better this way */
2943 for( j=0; j<stream->output.deviceCount; ++j )
2944 {
2945 mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[j], &stream->output.waveHeaders[j][i], sizeof(WAVEHDR) );
2946 if( mmresult != MMSYSERR_NOERROR )
2947 {
2948 result = paUnanticipatedHostError;
2949 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
2950 goto error;
2951 }
2952 }
2953 }
2954 stream->output.currentBufferIndex = 0;
2955 stream->output.framesUsedInCurrentBuffer = 0;
2956 }
2957
2958
2959 stream->isStopped = 0;
2960 stream->isActive = 1;
2961 stream->stopProcessing = 0;
2962 stream->abortProcessing = 0;
2963
2964 result = ResetEventWithPaError( stream->input.bufferEvent );
2965 if( result != paNoError ) goto error;
2966
2967 result = ResetEventWithPaError( stream->output.bufferEvent );
2968 if( result != paNoError ) goto error;
2969
2970
2971 if( stream->streamRepresentation.streamCallback )
2972 {
2973 /* callback stream */
2974
2975 result = ResetEventWithPaError( stream->abortEvent );
2976 if( result != paNoError ) goto error;
2977
2978 /* Create thread that waits for audio buffers to be ready for processing. */
2979 stream->processingThread = CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId );
2980 if( !stream->processingThread )
2981 {
2982 result = paUnanticipatedHostError;
2983 PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
2984 goto error;
2985 }
2986
2987 /** @todo could have mme specific stream parameters to allow the user
2988 to set the callback thread priorities */
2989 stream->highThreadPriority = THREAD_PRIORITY_TIME_CRITICAL;
2990 stream->throttledThreadPriority = THREAD_PRIORITY_NORMAL;
2991
2992 if( !SetThreadPriority( stream->processingThread, stream->highThreadPriority ) )
2993 {
2994 result = paUnanticipatedHostError;
2995 PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
2996 goto error;
2997 }
2998 stream->processingThreadPriority = stream->highThreadPriority;
2999 }
3000 else
3001 {
3002 /* blocking read/write stream */
3003
3004 }
3005
3006 if( PA_IS_INPUT_STREAM_(stream) )
3007 {
3008 for( i=0; i < stream->input.deviceCount; ++i )
3009 {
3010 mmresult = waveInStart( ((HWAVEIN*)stream->input.waveHandles)[i] );
3011 PA_DEBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult));
3012 if( mmresult != MMSYSERR_NOERROR )
3013 {
3014 result = paUnanticipatedHostError;
3015 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
3016 goto error;
3017 }
3018 }
3019 }
3020
3021 if( PA_IS_OUTPUT_STREAM_(stream) )
3022 {
3023 for( i=0; i < stream->output.deviceCount; ++i )
3024 {
3025 if( (mmresult = waveOutRestart( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
3026 {
3027 result = paUnanticipatedHostError;
3028 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
3029 goto error;
3030 }
3031 }
3032 }
3033
3034 return result;
3035
3036 error:
3037 /** @todo FIXME: implement recovery as best we can
3038 This should involve rolling back to a state as-if this function had never been called
3039 */
3040 return result;
3041 }
3042
3043
3044 static PaError StopStream( PaStream *s )
3045 {
3046 PaError result = paNoError;
3047 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3048 int timeout;
3049 DWORD waitResult;
3050 MMRESULT mmresult;
3051 signed int hostOutputBufferIndex;
3052 unsigned int channel, waitCount, i;
3053
3054 /** @todo
3055 REVIEW: the error checking in this function needs review. the basic
3056 idea is to return from this function in a known state - for example
3057 there is no point avoiding calling waveInReset just because
3058 the thread times out.
3059 */
3060
3061 if( stream->processingThread )
3062 {
3063 /* callback stream */
3064
3065 /* Tell processing thread to stop generating more data and to let current data play out. */
3066 stream->stopProcessing = 1;
3067
3068 /* Calculate timeOut longer than longest time it could take to return all buffers. */
3069 timeout = (int)(stream->allBuffersDurationMs * 1.5);
3070 if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
3071 timeout = PA_MME_MIN_TIMEOUT_MSEC_;
3072
3073 PA_DEBUG(("WinMME StopStream: waiting for background thread.\n"));
3074
3075 waitResult = WaitForSingleObject( stream->processingThread, timeout );
3076 if( waitResult == WAIT_TIMEOUT )
3077 {
3078 /* try to abort */
3079 stream->abortProcessing = 1;
3080 SetEvent( stream->abortEvent );
3081 waitResult = WaitForSingleObject( stream->processingThread, timeout );
3082 if( waitResult == WAIT_TIMEOUT )
3083 {
3084 PA_DEBUG(("WinMME StopStream: timed out while waiting for background thread to finish.\n"));
3085 result = paTimedOut;
3086 }
3087 }
3088
3089 CloseHandle( stream->processingThread );
3090 stream->processingThread = NULL;
3091 }
3092 else
3093 {
3094 /* blocking read / write stream */
3095
3096 if( PA_IS_OUTPUT_STREAM_(stream) )
3097 {
3098 if( stream->output.framesUsedInCurrentBuffer > 0 )
3099 {
3100 /* there are still unqueued frames in the current buffer, so flush them */
3101
3102 hostOutputBufferIndex = stream->output.currentBufferIndex;
3103
3104 PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
3105 stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
3106
3107 channel = 0;
3108 for( i=0; i<stream->output.deviceCount; ++i )
3109 {
3110 /* we have stored the number of channels in the buffer in dwUser */
3111 int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
3112
3113 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
3114 stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
3115 stream->output.framesUsedInCurrentBuffer * channelCount *
3116 stream->bufferProcessor.bytesPerHostOutputSample,
3117 channelCount );
3118
3119 channel += channelCount;
3120 }
3121
3122 PaUtil_ZeroOutput( &stream->bufferProcessor,
3123 stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
3124
3125 /* we send the entire buffer to the output devices, but we could
3126 just send a partial buffer, rather than zeroing the unused
3127 samples.
3128 */
3129 AdvanceToNextOutputBuffer( stream );
3130 }
3131
3132
3133 timeout = (stream->allBuffersDurationMs / stream->output.bufferCount) + 1;
3134 if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
3135 timeout = PA_MME_MIN_TIMEOUT_MSEC_;
3136
3137 waitCount = 0;
3138 while( !NoBuffersAreQueued( &stream->output ) && waitCount <= stream->output.bufferCount )
3139 {
3140 /* wait for MME to signal that a buffer is available */
3141 waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
3142 if( waitResult == WAIT_FAILED )
3143 {
3144 break;
3145 }
3146 else if( waitResult == WAIT_TIMEOUT )
3147 {
3148 /* keep waiting */
3149 }
3150
3151 ++waitCount;
3152 }
3153 }
3154 }
3155
3156 if( PA_IS_OUTPUT_STREAM_(stream) )
3157 {
3158 for( i =0; i < stream->output.deviceCount; ++i )
3159 {
3160 mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
3161 if( mmresult != MMSYSERR_NOERROR )
3162 {
3163 result = paUnanticipatedHostError;
3164 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
3165 }
3166 }
3167 }
3168
3169 if( PA_IS_INPUT_STREAM_(stream) )
3170 {
3171 for( i=0; i < stream->input.deviceCount; ++i )
3172 {
3173 mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
3174 if( mmresult != MMSYSERR_NOERROR )
3175 {
3176 result = paUnanticipatedHostError;
3177 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
3178 }
3179 }
3180 }
3181
3182 stream->isStopped = 1;
3183 stream->isActive = 0;
3184
3185 return result;
3186 }
3187
3188
3189 static PaError AbortStream( PaStream *s )
3190 {
3191 PaError result = paNoError;
3192 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3193 int timeout;
3194 DWORD waitResult;
3195 MMRESULT mmresult;
3196 unsigned int i;
3197
3198 /** @todo
3199 REVIEW: the error checking in this function needs review. the basic
3200 idea is to return from this function in a known state - for example
3201 there is no point avoiding calling waveInReset just because
3202 the thread times out.
3203 */
3204
3205 if( stream->processingThread )
3206 {
3207 /* callback stream */
3208
3209 /* Tell processing thread to abort immediately */
3210 stream->abortProcessing = 1;
3211 SetEvent( stream->abortEvent );
3212 }
3213
3214
3215 if( PA_IS_OUTPUT_STREAM_(stream) )
3216 {
3217 for( i =0; i < stream->output.deviceCount; ++i )
3218 {
3219 mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
3220 if( mmresult != MMSYSERR_NOERROR )
3221 {
3222 PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
3223 return paUnanticipatedHostError;
3224 }
3225 }
3226 }
3227
3228 if( PA_IS_INPUT_STREAM_(stream) )
3229 {
3230 for( i=0; i < stream->input.deviceCount; ++i )
3231 {
3232 mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
3233 if( mmresult != MMSYSERR_NOERROR )
3234 {
3235 PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
3236 return paUnanticipatedHostError;
3237 }
3238 }
3239 }
3240
3241
3242 if( stream->processingThread )
3243 {
3244 /* callback stream */
3245
3246 PA_DEBUG(("WinMME AbortStream: waiting for background thread.\n"));
3247
3248 /* Calculate timeOut longer than longest time it could take to return all buffers. */
3249 timeout = (int)(stream->allBuffersDurationMs * 1.5);
3250 if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
3251 timeout = PA_MME_MIN_TIMEOUT_MSEC_;
3252
3253 waitResult = WaitForSingleObject( stream->processingThread, timeout );
3254 if( waitResult == WAIT_TIMEOUT )
3255 {
3256 PA_DEBUG(("WinMME AbortStream: timed out while waiting for background thread to finish.\n"));
3257 return paTimedOut;
3258 }
3259
3260 CloseHandle( stream->processingThread );
3261 stream->processingThread = NULL;
3262 }
3263
3264 stream->isStopped = 1;
3265 stream->isActive = 0;
3266
3267 return result;
3268 }
3269
3270
3271 static PaError IsStreamStopped( PaStream *s )
3272 {
3273 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3274
3275 return stream->isStopped;
3276 }
3277
3278
3279 static PaError IsStreamActive( PaStream *s )
3280 {
3281 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3282
3283 return stream->isActive;
3284 }
3285
3286
3287 static PaTime GetStreamTime( PaStream *s )
3288 {
3289 (void) s; /* unused parameter */
3290
3291 return PaUtil_GetTime();
3292 }
3293
3294
3295 static double GetStreamCpuLoad( PaStream* s )
3296 {
3297 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3298
3299 return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
3300 }
3301
3302
3303 /*
3304 As separate stream interfaces are used for blocking and callback
3305 streams, the following functions can be guaranteed to only be called
3306 for blocking streams.
3307 */
3308
3309 static PaError ReadStream( PaStream* s,
3310 void *buffer,
3311 unsigned long frames )
3312 {
3313 PaError result = paNoError;
3314 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3315 void *userBuffer;
3316 unsigned long framesRead = 0;
3317 unsigned long framesProcessed;
3318 signed int hostInputBufferIndex;
3319 DWORD waitResult;
3320 DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
3321 unsigned int channel, i;
3322
3323 if( PA_IS_INPUT_STREAM_(stream) )
3324 {
3325 /* make a local copy of the user buffer pointer(s). this is necessary
3326 because PaUtil_CopyInput() advances these pointers every time
3327 it is called.
3328 */
3329 if( stream->bufferProcessor.userInputIsInterleaved )
3330 {
3331 userBuffer = buffer;
3332 }
3333 else
3334 {
3335 userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount );
3336 if( !userBuffer )
3337 return paInsufficientMemory;
3338 for( i = 0; i<stream->bufferProcessor.inputChannelCount; ++i )
3339 ((void**)userBuffer)[i] = ((void**)buffer)[i];
3340 }
3341
3342 do{
3343 if( CurrentInputBuffersAreDone( stream ) )
3344 {
3345 if( NoBuffersAreQueued( &stream->input ) )
3346 {
3347 /** @todo REVIEW: consider what to do if the input overflows.
3348 do we requeue all of the buffers? should we be running
3349 a thread to make sure they are always queued? */
3350
3351 result = paInputOverflowed;
3352 }
3353
3354 hostInputBufferIndex = stream->input.currentBufferIndex;
3355
3356 PaUtil_SetInputFrameCount( &stream->bufferProcessor,
3357 stream->input.framesPerBuffer - stream->input.framesUsedInCurrentBuffer );
3358
3359 channel = 0;
3360 for( i=0; i<stream->input.deviceCount; ++i )
3361 {
3362 /* we have stored the number of channels in the buffer in dwUser */
3363 int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
3364
3365 PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
3366 stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
3367 stream->input.framesUsedInCurrentBuffer * channelCount *
3368 stream->bufferProcessor.bytesPerHostInputSample,
3369 channelCount );
3370
3371 channel += channelCount;
3372 }
3373
3374 framesProcessed = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, frames - framesRead );
3375
3376 stream->input.framesUsedInCurrentBuffer += framesProcessed;
3377 if( stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
3378 {
3379 result = AdvanceToNextInputBuffer( stream );
3380 if( result != paNoError )
3381 break;
3382 }
3383
3384 framesRead += framesProcessed;
3385
3386 }else{
3387 /* wait for MME to signal that a buffer is available */
3388 waitResult = WaitForSingleObject( stream->input.bufferEvent, timeout );
3389 if( waitResult == WAIT_FAILED )
3390 {
3391 result = paUnanticipatedHostError;
3392 break;
3393 }
3394 else if( waitResult == WAIT_TIMEOUT )
3395 {
3396 /* if a timeout is encountered, continue,
3397 perhaps we should give up eventually
3398 */
3399 }
3400 }
3401 }while( framesRead < frames );
3402 }
3403 else
3404 {
3405 result = paCanNotReadFromAnOutputOnlyStream;
3406 }
3407
3408 return result;
3409 }
3410
3411
3412 static PaError WriteStream( PaStream* s,
3413 const void *buffer,
3414 unsigned long frames )
3415 {
3416 PaError result = paNoError;
3417 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3418 const void *userBuffer;
3419 unsigned long framesWritten = 0;
3420 unsigned long framesProcessed;
3421 signed int hostOutputBufferIndex;
3422 DWORD waitResult;
3423 DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
3424 unsigned int channel, i;
3425
3426
3427 if( PA_IS_OUTPUT_STREAM_(stream) )
3428 {
3429 /* make a local copy of the user buffer pointer(s). this is necessary
3430 because PaUtil_CopyOutput() advances these pointers every time
3431 it is called.
3432 */
3433 if( stream->bufferProcessor.userOutputIsInterleaved )
3434 {
3435 userBuffer = buffer;
3436 }
3437 else
3438 {
3439 userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount );
3440 if( !userBuffer )
3441 return paInsufficientMemory;
3442 for( i = 0; i<stream->bufferProcessor.outputChannelCount; ++i )
3443 ((const void**)userBuffer)[i] = ((const void**)buffer)[i];
3444 }
3445
3446 do{
3447 if( CurrentOutputBuffersAreDone( stream ) )
3448 {
3449 if( NoBuffersAreQueued( &stream->output ) )
3450 {
3451 /** @todo REVIEW: consider what to do if the output
3452 underflows. do we requeue all the existing buffers with
3453 zeros? should we run a separate thread to keep the buffers
3454 enqueued at all times? */
3455
3456 result = paOutputUnderflowed;
3457 }
3458
3459 hostOutputBufferIndex = stream->output.currentBufferIndex;
3460
3461 PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
3462 stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
3463
3464 channel = 0;
3465 for( i=0; i<stream->output.deviceCount; ++i )
3466 {
3467 /* we have stored the number of channels in the buffer in dwUser */
3468 int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
3469
3470 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
3471 stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
3472 stream->output.framesUsedInCurrentBuffer * channelCount *
3473 stream->bufferProcessor.bytesPerHostOutputSample,
3474 channelCount );
3475
3476 channel += channelCount;
3477 }
3478
3479 framesProcessed = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames - framesWritten );
3480
3481 stream->output.framesUsedInCurrentBuffer += framesProcessed;
3482 if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
3483 {
3484 result = AdvanceToNextOutputBuffer( stream );
3485 if( result != paNoError )
3486 break;
3487 }
3488
3489 framesWritten += framesProcessed;
3490 }
3491 else
3492 {
3493 /* wait for MME to signal that a buffer is available */
3494 waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
3495 if( waitResult == WAIT_FAILED )
3496 {
3497 result = paUnanticipatedHostError;
3498 break;
3499 }
3500 else if( waitResult == WAIT_TIMEOUT )
3501 {
3502 /* if a timeout is encountered, continue,
3503 perhaps we should give up eventually
3504 */
3505 }
3506 }
3507 }while( framesWritten < frames );
3508 }
3509 else
3510 {
3511 result = paCanNotWriteToAnInputOnlyStream;
3512 }
3513
3514 return result;
3515 }
3516
3517
3518 static signed long GetStreamReadAvailable( PaStream* s )
3519 {
3520 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3521
3522 if( PA_IS_INPUT_STREAM_(stream) )
3523 return GetAvailableFrames( &stream->input );
3524 else
3525 return paCanNotReadFromAnOutputOnlyStream;
3526 }
3527
3528
3529 static signed long GetStreamWriteAvailable( PaStream* s )
3530 {
3531 PaWinMmeStream *stream = (PaWinMmeStream*)s;
3532
3533 if( PA_IS_OUTPUT_STREAM_(stream) )
3534 return GetAvailableFrames( &stream->output );
3535 else
3536 return paCanNotWriteToAnInputOnlyStream;
3537 }
3538
3539
3540 /* NOTE: the following functions are MME-stream specific, and are called directly
3541 by client code. We need to check for many more error conditions here because
3542 we don't have the benefit of pa_front.c's parameter checking.
3543 */
3544
3545 static PaError GetWinMMEStreamPointer( PaWinMmeStream **stream, PaStream *s )
3546 {
3547 PaError result;
3548 PaUtilHostApiRepresentation *hostApi;
3549 PaWinMmeHostApiRepresentation *winMmeHostApi;
3550
3551 result = PaUtil_ValidateStreamPointer( s );
3552 if( result != paNoError )
3553 return result;
3554
3555 result = PaUtil_GetHostApiRepresentation( &hostApi, paMME );
3556 if( result != paNoError )
3557 return result;
3558
3559 winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
3560
3561 /* note, the following would be easier if there was a generic way of testing
3562 that a stream belongs to a specific host API */
3563
3564 if( PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->callbackStreamInterface
3565 || PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->blockingStreamInterface )
3566 {
3567 /* s is a WinMME stream */
3568 *stream = (PaWinMmeStream *)s;
3569 return paNoError;
3570 }
3571 else
3572 {
3573 return paIncompatibleStreamHostApi;
3574 }
3575 }
3576
3577
3578 int PaWinMME_GetStreamInputHandleCount( PaStream* s )
3579 {
3580 PaWinMmeStream *stream;
3581 PaError result = GetWinMMEStreamPointer( &stream, s );
3582
3583 if( result == paNoError )
3584 return (PA_IS_INPUT_STREAM_(stream)) ? stream->input.deviceCount : 0;
3585 else
3586 return result;
3587 }
3588
3589
3590 HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* s, int handleIndex )
3591 {
3592 PaWinMmeStream *stream;
3593 PaError result = GetWinMMEStreamPointer( &stream, s );
3594
3595 if( result == paNoError
3596 && PA_IS_INPUT_STREAM_(stream)
3597 && handleIndex >= 0
3598 && (unsigned int)handleIndex < stream->input.deviceCount )
3599 return ((HWAVEIN*)stream->input.waveHandles)[handleIndex];
3600 else
3601 return 0;
3602 }
3603
3604
3605 int PaWinMME_GetStreamOutputHandleCount( PaStream* s)
3606 {
3607 PaWinMmeStream *stream;
3608 PaError result = GetWinMMEStreamPointer( &stream, s );
3609
3610 if( result == paNoError )
3611 return (PA_IS_OUTPUT_STREAM_(stream)) ? stream->output.deviceCount : 0;
3612 else
3613 return result;
3614 }
3615
3616
3617 HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* s, int handleIndex )
3618 {
3619 PaWinMmeStream *stream;
3620 PaError result = GetWinMMEStreamPointer( &stream, s );
3621
3622 if( result == paNoError
3623 && PA_IS_OUTPUT_STREAM_(stream)
3624 && handleIndex >= 0
3625 && (unsigned int)handleIndex < stream->output.deviceCount )
3626 return ((HWAVEOUT*)stream->output.waveHandles)[handleIndex];
3627 else
3628 return 0;
3629 }
3630
3631
3632
3633
3634