Debian Codegraph @

3rdparty/iaxclient/lib/portaudio/src/hostapi/oss/pa_unix_oss.c

raw symbols SCIP
1 /*
2 * $Id: pa_unix_oss.c,v 1.1 2006/06/10 21:30:56 dmazzoni Exp $
3 * PortAudio Portable Real-Time Audio Library
4 * Latest Version at: http://www.portaudio.com
5 * OSS implementation by:
6 * Douglas Repetto
7 * Phil Burk
8 * Dominic Mazzoni
9 * Arve Knudsen
10 *
11 * Based on the Open Source API proposed by Ross Bencina
12 * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
13 *
14 * Permission is hereby granted, free of charge, to any person obtaining
15 * a copy of this software and associated documentation files
16 * (the "Software"), to deal in the Software without restriction,
17 * including without limitation the rights to use, copy, modify, merge,
18 * publish, distribute, sublicense, and/or sell copies of the Software,
19 * and to permit persons to whom the Software is furnished to do so,
20 * subject to the following conditions:
21 *
22 * The above copyright notice and this permission notice shall be
23 * included in all copies or substantial portions of the Software.
24 *
25 * Any person wishing to distribute modifications to the Software is
26 * requested to send the modifications to the original developer so that
27 * they can be incorporated into the canonical version.
28 *
29 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
32 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
33 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
34 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 */
37
38 #include <stdio.h>
39 #include <string.h>
40 #include <math.h>
41 #include <fcntl.h>
42 #include <sys/ioctl.h>
43 #include <unistd.h>
44 #include <pthread.h>
45 #include <alloca.h>
46 #include <malloc.h>
47 #include <assert.h>
48 #include <errno.h>
49 #include <sys/types.h>
50 #include <sys/stat.h>
51 #include <sys/poll.h>
52 #include <sys/select.h>
53 #include <limits.h>
54 #include <semaphore.h>
55
56 #ifdef __FreeBSD__
57 # include <sys/soundcard.h>
58 # define DEVICE_NAME_BASE "/dev/dsp"
59 #elif defined __linux__
60 # include <linux/soundcard.h>
61 # define DEVICE_NAME_BASE "/dev/dsp"
62 #else
63 # include <machine/soundcard.h> /* JH20010905 */
64 # define DEVICE_NAME_BASE "/dev/audio"
65 #endif
66
67 #include "portaudio.h"
68 #include "pa_util.h"
69 #include "pa_allocation.h"
70 #include "pa_hostapi.h"
71 #include "pa_stream.h"
72 #include "pa_cpuload.h"
73 #include "pa_process.h"
74 #include "pa_unix_util.h"
75
76 static int sysErr_;
77 static pthread_t mainThread_;
78
79 /* Check return value of system call, and map it to PaError */
80 #define ENSURE_(expr, code) \
81 do { \
82 if( UNLIKELY( (sysErr_ = (expr)) < 0 ) ) \
83 { \
84 /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
85 if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
86 { \
87 PaUtil_SetLastHostErrorInfo( paALSA, sysErr_, strerror( errno ) ); \
88 } \
89 \
90 PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
91 result = (code); \
92 goto error; \
93 } \
94 } while( 0 );
95
96 #ifndef AFMT_S16_NE
97 #define AFMT_S16_NE Get_AFMT_S16_NE()
98 /*********************************************************************
99 * Some versions of OSS do not define AFMT_S16_NE. So check CPU.
100 * PowerPC is Big Endian. X86 is Little Endian.
101 */
102 static int Get_AFMT_S16_NE( void )
103 {
104 long testData = 1;
105 char *ptr = (char *) &testData;
106 int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */
107 return isLittle ? AFMT_S16_LE : AFMT_S16_BE;
108 }
109 #endif
110
111 /* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */
112
113 typedef struct
114 {
115 PaUtilHostApiRepresentation inheritedHostApiRep;
116 PaUtilStreamInterface callbackStreamInterface;
117 PaUtilStreamInterface blockingStreamInterface;
118
119 PaUtilAllocationGroup *allocations;
120
121 PaHostApiIndex hostApiIndex;
122 }
123 PaOSSHostApiRepresentation;
124
125 /** Per-direction structure for PaOssStream.
126 *
127 * Aspect StreamChannels: In case the user requests to open the same device for both capture and playback,
128 * but with different number of channels we will have to adapt between the number of user and host
129 * channels for at least one direction, since the configuration space is the same for both directions
130 * of an OSS device.
131 */
132 typedef struct
133 {
134 int fd;
135 const char *devName;
136 int userChannelCount, hostChannelCount;
137 int userInterleaved;
138 void *buffer;
139 PaSampleFormat userFormat, hostFormat;
140 double latency;
141 unsigned long hostFrames, numBufs;
142 void **userBuffers; /* For non-interleaved blocking */
143 } PaOssStreamComponent;
144
145 /** Implementation specific representation of a PaStream.
146 *
147 */
148 typedef struct PaOssStream
149 {
150 PaUtilStreamRepresentation streamRepresentation;
151 PaUtilCpuLoadMeasurer cpuLoadMeasurer;
152 PaUtilBufferProcessor bufferProcessor;
153
154 PaUtilThreading threading;
155
156 int sharedDevice;
157 unsigned long framesPerHostBuffer;
158 int triggered; /* Have the devices been triggered yet (first start) */
159
160 int isActive;
161 int isStopped;
162
163 int lastPosPtr;
164 double lastStreamBytes;
165
166 int framesProcessed;
167
168 double sampleRate;
169
170 int callbackMode;
171 int callbackStop, callbackAbort;
172
173 PaOssStreamComponent *capture, *playback;
174 unsigned long pollTimeout;
175 sem_t semaphore;
176 }
177 PaOssStream;
178
179 typedef enum {
180 StreamMode_In,
181 StreamMode_Out
182 } StreamMode;
183
184 /* prototypes for functions declared in this file */
185
186 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
187 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
188 const PaStreamParameters *inputParameters,
189 const PaStreamParameters *outputParameters,
190 double sampleRate );
191 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
192 PaStream** s,
193 const PaStreamParameters *inputParameters,
194 const PaStreamParameters *outputParameters,
195 double sampleRate,
196 unsigned long framesPerBuffer,
197 PaStreamFlags streamFlags,
198 PaStreamCallback *streamCallback,
199 void *userData );
200 static PaError CloseStream( PaStream* stream );
201 static PaError StartStream( PaStream *stream );
202 static PaError StopStream( PaStream *stream );
203 static PaError AbortStream( PaStream *stream );
204 static PaError IsStreamStopped( PaStream *s );
205 static PaError IsStreamActive( PaStream *stream );
206 static PaTime GetStreamTime( PaStream *stream );
207 static double GetStreamCpuLoad( PaStream* stream );
208 static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
209 static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
210 static signed long GetStreamReadAvailable( PaStream* stream );
211 static signed long GetStreamWriteAvailable( PaStream* stream );
212 static PaError BuildDeviceList( PaOSSHostApiRepresentation *hostApi );
213
214
215 /** Initialize the OSS API implementation.
216 *
217 * This function will initialize host API datastructures and query host devices for information.
218 *
219 * Aspect DeviceCapabilities: Enumeration of host API devices is initiated from here
220 *
221 * Aspect FreeResources: If an error is encountered under way we have to free each resource allocated in this function,
222 * this happens with the usual "error" label.
223 */
224 PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
225 {
226 PaError result = paNoError;
227 PaOSSHostApiRepresentation *ossHostApi = NULL;
228
229 PA_UNLESS( ossHostApi = (PaOSSHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaOSSHostApiRepresentation) ),
230 paInsufficientMemory );
231 PA_UNLESS( ossHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
232 ossHostApi->hostApiIndex = hostApiIndex;
233
234 /* Initialize host API structure */
235 *hostApi = &ossHostApi->inheritedHostApiRep;
236 (*hostApi)->info.structVersion = 1;
237 (*hostApi)->info.type = paOSS;
238 (*hostApi)->info.name = "OSS";
239 (*hostApi)->Terminate = Terminate;
240 (*hostApi)->OpenStream = OpenStream;
241 (*hostApi)->IsFormatSupported = IsFormatSupported;
242
243 PA_ENSURE( BuildDeviceList( ossHostApi ) );
244
245 PaUtil_InitializeStreamInterface( &ossHostApi->callbackStreamInterface, CloseStream, StartStream,
246 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
247 GetStreamTime, GetStreamCpuLoad,
248 PaUtil_DummyRead, PaUtil_DummyWrite,
249 PaUtil_DummyGetReadAvailable,
250 PaUtil_DummyGetWriteAvailable );
251
252 PaUtil_InitializeStreamInterface( &ossHostApi->blockingStreamInterface, CloseStream, StartStream,
253 StopStream, AbortStream, IsStreamStopped, IsStreamActive,
254 GetStreamTime, PaUtil_DummyGetCpuLoad,
255 ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
256
257 mainThread_ = pthread_self();
258
259 return result;
260
261 error:
262 if( ossHostApi )
263 {
264 if( ossHostApi->allocations )
265 {
266 PaUtil_FreeAllAllocations( ossHostApi->allocations );
267 PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
268 }
269
270 PaUtil_FreeMemory( ossHostApi );
271 }
272 return result;
273 }
274
275 PaError PaUtil_InitializeDeviceInfo( PaDeviceInfo *deviceInfo, const char *name, PaHostApiIndex hostApiIndex, int maxInputChannels,
276 int maxOutputChannels, PaTime defaultLowInputLatency, PaTime defaultLowOutputLatency, PaTime defaultHighInputLatency,
277 PaTime defaultHighOutputLatency, double defaultSampleRate, PaUtilAllocationGroup *allocations )
278 {
279 PaError result = paNoError;
280
281 deviceInfo->structVersion = 2;
282 if( allocations )
283 {
284 size_t len = strlen( name ) + 1;
285 PA_UNLESS( deviceInfo->name = PaUtil_GroupAllocateMemory( allocations, len ), paInsufficientMemory );
286 strncpy( (char *)deviceInfo->name, name, len );
287 }
288 else
289 deviceInfo->name = name;
290
291 deviceInfo->hostApi = hostApiIndex;
292 deviceInfo->maxInputChannels = maxInputChannels;
293 deviceInfo->maxOutputChannels = maxOutputChannels;
294 deviceInfo->defaultLowInputLatency = defaultLowInputLatency;
295 deviceInfo->defaultLowOutputLatency = defaultLowOutputLatency;
296 deviceInfo->defaultHighInputLatency = defaultHighInputLatency;
297 deviceInfo->defaultHighOutputLatency = defaultHighOutputLatency;
298 deviceInfo->defaultSampleRate = defaultSampleRate;
299
300 error:
301 return result;
302 }
303
304 static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount,
305 double *defaultLowLatency, double *defaultHighLatency )
306 {
307 PaError result = paNoError;
308 int numChannels, maxNumChannels;
309 int busy = 0;
310 int devHandle = -1;
311 int sr;
312 *maxChannelCount = 0; /* Default value in case this fails */
313
314 if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK )) < 0 )
315 {
316 if( errno == EBUSY || errno == EAGAIN )
317 {
318 PA_DEBUG(( "%s: Device %s busy\n", __FUNCTION__, deviceName ));
319 }
320 else
321 {
322 PA_DEBUG(( "%s: Can't access device: %s\n", __FUNCTION__, strerror( errno ) ));
323 }
324
325 return paDeviceUnavailable;
326 }
327
328 /* Negotiate for the maximum number of channels for this device. PLB20010927
329 * Consider up to 16 as the upper number of channels.
330 * Variable maxNumChannels should contain the actual upper limit after the call.
331 * Thanks to John Lazzaro and Heiko Purnhagen for suggestions.
332 */
333 maxNumChannels = 0;
334 for( numChannels = 1; numChannels <= 16; numChannels++ )
335 {
336 int temp = numChannels;
337 if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 )
338 {
339 busy = EAGAIN == errno || EBUSY == errno;
340 /* ioctl() failed so bail out if we already have stereo */
341 if( maxNumChannels >= 2 )
342 break;
343 }
344 else
345 {
346 /* ioctl() worked but bail out if it does not support numChannels.
347 * We don't want to leave gaps in the numChannels supported.
348 */
349 if( (numChannels > 2) && (temp != numChannels) )
350 break;
351 if( temp > maxNumChannels )
352 maxNumChannels = temp; /* Save maximum. */
353 }
354 }
355 /* A: We're able to open a device for capture if it's busy playing back and vice versa,
356 * but we can't configure anything */
357 if( 0 == maxNumChannels && busy )
358 {
359 result = paDeviceUnavailable;
360 goto error;
361 }
362
363 /* The above negotiation may fail for an old driver so try this older technique. */
364 if( maxNumChannels < 1 )
365 {
366 int stereo = 1;
367 if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 )
368 {
369 maxNumChannels = 1;
370 }
371 else
372 {
373 maxNumChannels = (stereo) ? 2 : 1;
374 }
375 PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels ))
376 }
377
378 /* During channel negotiation, the last ioctl() may have failed. This can
379 * also cause sample rate negotiation to fail. Hence the following, to return
380 * to a supported number of channels. SG20011005 */
381 {
382 /* use most reasonable default value */
383 int temp = PA_MIN( maxNumChannels, 2 );
384 ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ), paUnanticipatedHostError );
385 }
386
387 /* Get supported sample rate closest to 44100 Hz */
388 if( *defaultSampleRate < 0 )
389 {
390 sr = 44100;
391 if( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ) < 0 )
392 {
393 result = paUnanticipatedHostError;
394 goto error;
395 }
396
397 *defaultSampleRate = sr;
398 }
399
400 *maxChannelCount = maxNumChannels;
401 /* TODO */
402 *defaultLowLatency = 512. / *defaultSampleRate;
403 *defaultHighLatency = 2048. / *defaultSampleRate;
404
405 error:
406 if( devHandle >= 0 )
407 close( devHandle );
408
409 return result;
410 }
411
412 /** Query OSS device.
413 *
414 * This is where PaDeviceInfo objects are constructed and filled in with relevant information.
415 *
416 * Aspect DeviceCapabilities: The inferred device capabilities are recorded in a PaDeviceInfo object that is constructed
417 * in place.
418 */
419 static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo )
420 {
421 PaError result = paNoError;
422 double sampleRate = -1.;
423 int maxInputChannels, maxOutputChannels;
424 PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency;
425 PaError tmpRes = paNoError;
426 int busy = 0;
427 *deviceInfo = NULL;
428
429 /* douglas:
430 we have to do this querying in a slightly different order. apparently
431 some sound cards will give you different info based on their settins.
432 e.g. a card might give you stereo at 22kHz but only mono at 44kHz.
433 the correct order for OSS is: format, channels, sample rate
434 */
435
436 /* Aspect StreamChannels: The number of channels supported for a device may depend on the mode it is
437 * opened in, it may have more channels available for capture than playback and vice versa. Therefore
438 * we will open the device in both read- and write-only mode to determine the supported number.
439 */
440 if( (tmpRes = QueryDirection( deviceName, StreamMode_In, &sampleRate, &maxInputChannels, &defaultLowInputLatency,
441 &defaultHighInputLatency )) != paNoError )
442 {
443 if( tmpRes != paDeviceUnavailable )
444 {
445 PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName ));
446 /* PA_ENSURE( tmpRes ); */
447 }
448 ++busy;
449 }
450 if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency,
451 &defaultHighOutputLatency )) != paNoError )
452 {
453 if( tmpRes != paDeviceUnavailable )
454 {
455 PA_DEBUG(( "%s: Querying device %s for playback failed!\n", __FUNCTION__, deviceName ));
456 /* PA_ENSURE( tmpRes ); */
457 }
458 ++busy;
459 }
460 assert( 0 <= busy && busy <= 2 );
461 if( 2 == busy ) /* Both directions are unavailable to us */
462 {
463 result = paDeviceUnavailable;
464 goto error;
465 }
466
467 PA_UNLESS( *deviceInfo = PaUtil_GroupAllocateMemory( ossApi->allocations, sizeof (PaDeviceInfo) ), paInsufficientMemory );
468 PA_ENSURE( PaUtil_InitializeDeviceInfo( *deviceInfo, deviceName, ossApi->hostApiIndex, maxInputChannels, maxOutputChannels,
469 defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency, sampleRate,
470 ossApi->allocations ) );
471
472 error:
473 return result;
474 }
475
476 /** Query host devices.
477 *
478 * Loop over host devices and query their capabilitiesu
479 *
480 * Aspect DeviceCapabilities: This function calls QueryDevice on each device entry and receives a filled in PaDeviceInfo object
481 * per device, these are placed in the host api representation's deviceInfos array.
482 */
483 static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi )
484 {
485 PaError result = paNoError;
486 PaUtilHostApiRepresentation *commonApi = &ossApi->inheritedHostApiRep;
487 int i;
488 int numDevices = 0, maxDeviceInfos = 1;
489 PaDeviceInfo **deviceInfos = NULL;
490
491 /* These two will be set to the first working input and output device, respectively */
492 commonApi->info.defaultInputDevice = paNoDevice;
493 commonApi->info.defaultOutputDevice = paNoDevice;
494
495 /* Find devices by calling QueryDevice on each
496 * potential device names. When we find a valid one,
497 * add it to a linked list.
498 * A: Can there only be 10 devices? */
499
500 for( i = 0; i < 10; i++ )
501 {
502 char deviceName[32];
503 PaDeviceInfo *deviceInfo;
504 int testResult;
505 struct stat stbuf;
506
507 if( i == 0 )
508 snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE);
509 else
510 snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i);
511
512 /* PA_DEBUG(("PaOSS BuildDeviceList: trying device %s\n", deviceName )); */
513 if( stat( deviceName, &stbuf ) < 0 )
514 {
515 if( ENOENT != errno )
516 PA_DEBUG(( "%s: Error stat'ing %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));
517 continue;
518 }
519 if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError )
520 {
521 if( testResult != paDeviceUnavailable )
522 PA_ENSURE( testResult );
523
524 continue;
525 }
526
527 ++numDevices;
528 if( !deviceInfos || numDevices > maxDeviceInfos )
529 {
530 maxDeviceInfos *= 2;
531 PA_UNLESS( deviceInfos = (PaDeviceInfo **) realloc( deviceInfos, maxDeviceInfos * sizeof (PaDeviceInfo *) ),
532 paInsufficientMemory );
533 }
534 {
535 int devIdx = numDevices - 1;
536 deviceInfos[devIdx] = deviceInfo;
537
538 if( commonApi->info.defaultInputDevice == paNoDevice && deviceInfo->maxInputChannels > 0 )
539 commonApi->info.defaultInputDevice = devIdx;
540 if( commonApi->info.defaultOutputDevice == paNoDevice && deviceInfo->maxOutputChannels > 0 )
541 commonApi->info.defaultOutputDevice = devIdx;
542 }
543 }
544
545 /* Make an array of PaDeviceInfo pointers out of the linked list */
546
547 PA_DEBUG(("PaOSS %s: Total number of devices found: %d\n", __FUNCTION__, numDevices));
548
549 commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
550 ossApi->allocations, sizeof(PaDeviceInfo*) * numDevices );
551 memcpy( commonApi->deviceInfos, deviceInfos, numDevices * sizeof (PaDeviceInfo *) );
552
553 commonApi->info.deviceCount = numDevices;
554
555 error:
556 free( deviceInfos );
557
558 return result;
559 }
560
561 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
562 {
563 PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
564
565 if( ossHostApi->allocations )
566 {
567 PaUtil_FreeAllAllocations( ossHostApi->allocations );
568 PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
569 }
570
571 PaUtil_FreeMemory( ossHostApi );
572 }
573
574 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
575 const PaStreamParameters *inputParameters,
576 const PaStreamParameters *outputParameters,
577 double sampleRate )
578 {
579 PaError result = paNoError;
580 PaDeviceIndex device;
581 PaDeviceInfo *deviceInfo;
582 char *deviceName;
583 int inputChannelCount, outputChannelCount;
584 int tempDevHandle = -1;
585 int flags;
586 PaSampleFormat inputSampleFormat, outputSampleFormat;
587
588 if( inputParameters )
589 {
590 inputChannelCount = inputParameters->channelCount;
591 inputSampleFormat = inputParameters->sampleFormat;
592
593 /* unless alternate device specification is supported, reject the use of
594 paUseHostApiSpecificDeviceSpecification */
595
596 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
597 return paInvalidDevice;
598
599 /* check that input device can support inputChannelCount */
600 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
601 return paInvalidChannelCount;
602
603 /* validate inputStreamInfo */
604 if( inputParameters->hostApiSpecificStreamInfo )
605 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
606 }
607 else
608 {
609 inputChannelCount = 0;
610 }
611
612 if( outputParameters )
613 {
614 outputChannelCount = outputParameters->channelCount;
615 outputSampleFormat = outputParameters->sampleFormat;
616
617 /* unless alternate device specification is supported, reject the use of
618 paUseHostApiSpecificDeviceSpecification */
619
620 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
621 return paInvalidDevice;
622
623 /* check that output device can support inputChannelCount */
624 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
625 return paInvalidChannelCount;
626
627 /* validate outputStreamInfo */
628 if( outputParameters->hostApiSpecificStreamInfo )
629 return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
630 }
631 else
632 {
633 outputChannelCount = 0;
634 }
635
636 if (inputChannelCount == 0 && outputChannelCount == 0)
637 return paInvalidChannelCount;
638
639 /* if full duplex, make sure that they're the same device */
640
641 if (inputChannelCount > 0 && outputChannelCount > 0 &&
642 inputParameters->device != outputParameters->device)
643 return paInvalidDevice;
644
645 /* if full duplex, also make sure that they're the same number of channels */
646
647 if (inputChannelCount > 0 && outputChannelCount > 0 &&
648 inputChannelCount != outputChannelCount)
649 return paInvalidChannelCount;
650
651 /* open the device so we can do more tests */
652
653 if( inputChannelCount > 0 )
654 {
655 result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi);
656 if (result != paNoError)
657 return result;
658 }
659 else
660 {
661 result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi);
662 if (result != paNoError)
663 return result;
664 }
665
666 deviceInfo = hostApi->deviceInfos[device];
667 deviceName = (char *)deviceInfo->name;
668
669 flags = O_NONBLOCK;
670 if (inputChannelCount > 0 && outputChannelCount > 0)
671 flags |= O_RDWR;
672 else if (inputChannelCount > 0)
673 flags |= O_RDONLY;
674 else
675 flags |= O_WRONLY;
676
677 ENSURE_( tempDevHandle = open( deviceInfo->name, flags ), paDeviceUnavailable );
678
679 /* PaOssStream_Configure will do the rest of the checking for us */
680 /* PA_ENSURE( PaOssStream_Configure( tempDevHandle, deviceName, outputChannelCount, &sampleRate ) ); */
681
682 /* everything succeeded! */
683
684 error:
685 if( tempDevHandle >= 0 )
686 close( tempDevHandle );
687
688 return result;
689 }
690
691 /** Validate stream parameters.
692 *
693 * Aspect StreamChannels: We verify that the number of channels is within the allowed range for the device
694 */
695 static PaError ValidateParameters( const PaStreamParameters *parameters, const PaDeviceInfo *deviceInfo, StreamMode mode )
696 {
697 int maxChans;
698
699 assert( parameters );
700
701 if( parameters->device == paUseHostApiSpecificDeviceSpecification )
702 {
703 return paInvalidDevice;
704 }
705
706 maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels :
707 deviceInfo->maxOutputChannels);
708 if( parameters->channelCount > maxChans )
709 {
710 return paInvalidChannelCount;
711 }
712
713 return paNoError;
714 }
715
716 static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters,
717 int callbackMode, int fd, const char *deviceName )
718 {
719 PaError result = paNoError;
720 assert( component );
721
722 memset( component, 0, sizeof (PaOssStreamComponent) );
723
724 component->fd = fd;
725 component->devName = deviceName;
726 component->userChannelCount = parameters->channelCount;
727 component->userFormat = parameters->sampleFormat;
728 component->latency = parameters->suggestedLatency;
729 component->userInterleaved = !(parameters->sampleFormat & paNonInterleaved);
730
731 if( !callbackMode && !component->userInterleaved )
732 {
733 /* Pre-allocate non-interleaved user provided buffers */
734 PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ),
735 paInsufficientMemory );
736 }
737
738 error:
739 return result;
740 }
741
742 static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component )
743 {
744 assert( component );
745
746 if( component->fd >= 0 )
747 close( component->fd );
748 if( component->buffer )
749 PaUtil_FreeMemory( component->buffer );
750
751 if( component->userBuffers )
752 PaUtil_FreeMemory( component->userBuffers );
753
754 PaUtil_FreeMemory( component );
755 }
756
757 static PaError ModifyBlocking( int fd, int blocking )
758 {
759 PaError result = paNoError;
760 int fflags;
761
762 ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError );
763
764 if( blocking )
765 fflags &= ~O_NONBLOCK;
766 else
767 fflags |= O_NONBLOCK;
768
769 ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError );
770
771 error:
772 return result;
773 }
774
775 static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev )
776 {
777 PaError result = paNoError;
778 int flags = O_NONBLOCK, duplex = 0;
779 int enableBits = 0;
780 *idev = *odev = -1;
781
782 if( idevName && odevName )
783 {
784 duplex = 1;
785 flags |= O_RDWR;
786 }
787 else if( idevName )
788 flags |= O_RDONLY;
789 else
790 flags |= O_WRONLY;
791
792 /* open first in nonblocking mode, in case it's busy...
793 * A: then unset the non-blocking attribute */
794 assert( flags & O_NONBLOCK );
795 if( idevName )
796 {
797 ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable );
798 PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */
799
800 /* Initially disable */
801 enableBits = ~PCM_ENABLE_INPUT;
802 ENSURE_( ioctl( *idev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
803 }
804 if( odevName )
805 {
806 if( !idevName )
807 {
808 ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable );
809 PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */
810
811 /* Initially disable */
812 enableBits = ~PCM_ENABLE_OUTPUT;
813 ENSURE_( ioctl( *odev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
814 }
815 else
816 {
817 ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError );
818 }
819 }
820
821 error:
822 return result;
823 }
824
825 static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters,
826 PaStreamCallback callback, void *userData, PaStreamFlags streamFlags,
827 PaOSSHostApiRepresentation *ossApi )
828 {
829 PaError result = paNoError;
830 int idev, odev;
831 PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep;
832 const char *idevName = NULL, *odevName = NULL;
833
834 assert( stream );
835
836 memset( stream, 0, sizeof (PaOssStream) );
837 stream->isStopped = 1;
838
839 PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) );
840
841 if( inputParameters && outputParameters )
842 {
843 if( inputParameters->device == outputParameters->device )
844 stream->sharedDevice = 1;
845 }
846
847 if( inputParameters )
848 idevName = hostApi->deviceInfos[inputParameters->device]->name;
849 if( outputParameters )
850 odevName = hostApi->deviceInfos[outputParameters->device]->name;
851 PA_ENSURE( OpenDevices( idevName, odevName, &idev, &odev ) );
852 if( inputParameters )
853 {
854 PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
855 PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) );
856 }
857 if( outputParameters )
858 {
859 PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
860 PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) );
861 }
862
863 if( callback != NULL )
864 {
865 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
866 &ossApi->callbackStreamInterface, callback, userData );
867 stream->callbackMode = 1;
868 }
869 else
870 {
871 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
872 &ossApi->blockingStreamInterface, callback, userData );
873 }
874
875 ENSURE_( sem_init( &stream->semaphore, 0, 0 ), paInternalError );
876
877 error:
878 return result;
879 }
880
881 static void PaOssStream_Terminate( PaOssStream *stream )
882 {
883 assert( stream );
884
885 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
886 PaUtil_TerminateThreading( &stream->threading );
887
888 if( stream->capture )
889 PaOssStreamComponent_Terminate( stream->capture );
890 if( stream->playback )
891 PaOssStreamComponent_Terminate( stream->playback );
892
893 sem_destroy( &stream->semaphore );
894
895 PaUtil_FreeMemory( stream );
896 }
897
898 /** Translate from PA format to OSS native.
899 *
900 */
901 static PaError Pa2OssFormat( PaSampleFormat paFormat, int *ossFormat )
902 {
903 switch( paFormat )
904 {
905 case paUInt8:
906 *ossFormat = AFMT_U8;
907 break;
908 case paInt8:
909 *ossFormat = AFMT_S8;
910 break;
911 case paInt16:
912 *ossFormat = AFMT_S16_NE;
913 break;
914 default:
915 return paInternalError; /* This shouldn't happen */
916 }
917
918 return paNoError;
919 }
920
921 /** Return the PA-compatible formats that this device can support.
922 *
923 */
924 static PaError GetAvailableFormats( PaOssStreamComponent *component, PaSampleFormat *availableFormats )
925 {
926 PaError result = paNoError;
927 int mask = 0;
928 PaSampleFormat frmts = 0;
929
930 ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETFMTS, &mask ), paUnanticipatedHostError );
931 if( mask & AFMT_U8 )
932 frmts |= paUInt8;
933 if( mask & AFMT_S8 )
934 frmts |= paInt8;
935 if( mask & AFMT_S16_NE )
936 frmts |= paInt16;
937 else
938 result = paSampleFormatNotSupported;
939
940 *availableFormats = frmts;
941
942 error:
943 return result;
944 }
945
946 static unsigned int PaOssStreamComponent_FrameSize( PaOssStreamComponent *component )
947 {
948 return Pa_GetSampleSize( component->hostFormat ) * component->hostChannelCount;
949 }
950
951 /** Buffer size in bytes.
952 *
953 */
954 static unsigned long PaOssStreamComponent_BufferSize( PaOssStreamComponent *component )
955 {
956 return PaOssStreamComponent_FrameSize( component ) * component->hostFrames * component->numBufs;
957 }
958
959 static int CalcHigherLogTwo( int n )
960 {
961 int log2 = 0;
962 while( (1<<log2) < n ) log2++;
963 return log2;
964 }
965
966 static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long framesPerBuffer,
967 StreamMode streamMode, PaOssStreamComponent *master )
968 {
969 PaError result = paNoError;
970 int temp, nativeFormat;
971 int sr = (int)sampleRate;
972 PaSampleFormat availableFormats, hostFormat;
973 int chans = component->userChannelCount;
974 int frgmt;
975 int numBufs;
976 int bytesPerBuf;
977 double bufSz;
978 unsigned long fragSz;
979 audio_buf_info bufInfo;
980
981 /* We may have a situation where only one component (the master) is configured, if both point to the same device.
982 * In that case, the second component will copy settings from the other */
983 if( !master )
984 {
985 /* Aspect BufferSettings: If framesPerBuffer is unspecified we have to infer a suitable fragment size.
986 * The hardware need not respect the requested fragment size, so we may have to adapt.
987 */
988 if( framesPerBuffer == paFramesPerBufferUnspecified )
989 {
990 bufSz = component->latency * sampleRate;
991 fragSz = bufSz / 4;
992 }
993 else
994 {
995 fragSz = framesPerBuffer;
996 bufSz = component->latency * sampleRate + fragSz; /* Latency + 1 buffer */
997 }
998
999 PA_ENSURE( GetAvailableFormats( component, &availableFormats ) );
1000 hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, component->userFormat );
1001
1002 /* OSS demands at least 2 buffers, and 16 bytes per buffer */
1003 numBufs = PA_MAX( bufSz / fragSz, 2 );
1004 bytesPerBuf = PA_MAX( fragSz * Pa_GetSampleSize( hostFormat ) * chans, 16 );
1005
1006 /* The fragment parameters are encoded like this:
1007 * Most significant byte: number of fragments
1008 * Least significant byte: exponent of fragment size (i.e., for 256, 8)
1009 */
1010 frgmt = (numBufs << 16) + (CalcHigherLogTwo( bytesPerBuf ) & 0xffff);
1011 ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );
1012
1013 /* A: according to the OSS programmer's guide parameters should be set in this order:
1014 * format, channels, rate */
1015
1016 /* This format should be deemed good before we get this far */
1017 PA_ENSURE( Pa2OssFormat( hostFormat, &temp ) );
1018 nativeFormat = temp;
1019 ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFMT, &temp ), paUnanticipatedHostError );
1020 PA_UNLESS( temp == nativeFormat, paInternalError );
1021
1022 /* try to set the number of channels */
1023 ENSURE_( ioctl( component->fd, SNDCTL_DSP_CHANNELS, &chans ), paSampleFormatNotSupported ); /* XXX: Should be paInvalidChannelCount? */
1024 /* It's possible that the minimum number of host channels is greater than what the user requested */
1025 PA_UNLESS( chans >= component->userChannelCount, paInvalidChannelCount );
1026
1027 /* try to set the sample rate */
1028 ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate );
1029
1030 /* reject if there's no sample rate within 1% of the one requested */
1031 if( (fabs( sampleRate - sr ) / sampleRate) > 0.01 )
1032 {
1033 PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
1034 PA_ENSURE( paInvalidSampleRate );
1035 }
1036
1037 ENSURE_( ioctl( component->fd, streamMode == StreamMode_In ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &bufInfo ),
1038 paUnanticipatedHostError );
1039 component->numBufs = bufInfo.fragstotal;
1040
1041 /* This needs to be the last ioctl call before the first read/write, according to the OSS programmer's guide */
1042 ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETBLKSIZE, &bytesPerBuf ), paUnanticipatedHostError );
1043
1044 component->hostFrames = bytesPerBuf / Pa_GetSampleSize( hostFormat ) / chans;
1045 component->hostChannelCount = chans;
1046 component->hostFormat = hostFormat;
1047 }
1048 else
1049 {
1050 component->hostFormat = master->hostFormat;
1051 component->hostFrames = master->hostFrames;
1052 component->hostChannelCount = master->hostChannelCount;
1053 component->numBufs = master->numBufs;
1054 }
1055
1056 PA_UNLESS( component->buffer = PaUtil_AllocateMemory( PaOssStreamComponent_BufferSize( component ) ),
1057 paInsufficientMemory );
1058
1059 error:
1060 return result;
1061 }
1062
1063 static PaError PaOssStreamComponent_Read( PaOssStreamComponent *component, unsigned long *frames )
1064 {
1065 PaError result = paNoError;
1066 size_t len = *frames * PaOssStreamComponent_FrameSize( component );
1067 ssize_t bytesRead;
1068
1069 ENSURE_( bytesRead = read( component->fd, component->buffer, len ), paUnanticipatedHostError );
1070 *frames = bytesRead / PaOssStreamComponent_FrameSize( component );
1071 /* TODO: Handle condition where number of frames read doesn't equal number of frames requested */
1072
1073 error:
1074 return result;
1075 }
1076
1077 static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames )
1078 {
1079 PaError result = paNoError;
1080 size_t len = *frames * PaOssStreamComponent_FrameSize( component );
1081 ssize_t bytesWritten;
1082
1083 ENSURE_( bytesWritten = write( component->fd, component->buffer, len ), paUnanticipatedHostError );
1084 *frames = bytesWritten / PaOssStreamComponent_FrameSize( component );
1085 /* TODO: Handle condition where number of frames written doesn't equal number of frames requested */
1086
1087 error:
1088 return result;
1089 }
1090
1091 /** Configure the stream according to input/output parameters.
1092 *
1093 * Aspect StreamChannels: The minimum number of channels supported by the device may exceed that requested by
1094 * the user, if so we'll record the actual number of host channels and adapt later.
1095 */
1096 static PaError PaOssStream_Configure( PaOssStream *stream, double sampleRate, unsigned long framesPerBuffer,
1097 double *inputLatency, double *outputLatency )
1098 {
1099 PaError result = paNoError;
1100 int duplex = stream->capture && stream->playback;
1101 unsigned long framesPerHostBuffer = 0;
1102
1103 /* We should request full duplex first thing after opening the device */
1104 if( duplex && stream->sharedDevice )
1105 ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETDUPLEX, 0 ), paUnanticipatedHostError );
1106
1107 if( stream->capture )
1108 {
1109 PaOssStreamComponent *component = stream->capture;
1110 PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_In, NULL );
1111
1112 assert( component->hostChannelCount > 0 );
1113 assert( component->hostFrames > 0 );
1114
1115 *inputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate;
1116 }
1117 if( stream->playback )
1118 {
1119 PaOssStreamComponent *component = stream->playback, *master = stream->sharedDevice ? stream->capture : NULL;
1120 PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_Out,
1121 master ) );
1122
1123 assert( component->hostChannelCount > 0 );
1124 assert( component->hostFrames > 0 );
1125
1126 *outputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate;
1127 }
1128
1129 if( duplex )
1130 framesPerHostBuffer = PA_MIN( stream->capture->hostFrames, stream->playback->hostFrames );
1131 else if( stream->capture )
1132 framesPerHostBuffer = stream->capture->hostFrames;
1133 else if( stream->playback )
1134 framesPerHostBuffer = stream->playback->hostFrames;
1135
1136 stream->framesPerHostBuffer = framesPerHostBuffer;
1137 stream->pollTimeout = (int) ceil( 1e6 * framesPerHostBuffer / sampleRate ); /* Period in usecs, rounded up */
1138
1139 stream->sampleRate = stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
1140
1141 error:
1142 return result;
1143 }
1144
1145 /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
1146
1147 /** Open a PA OSS stream.
1148 *
1149 * Aspect StreamChannels: The number of channels is specified per direction (in/out), and can differ between the
1150 * two. However, OSS doesn't support separate configuration spaces for capture and playback so if both
1151 * directions are the same device we will demand the same number of channels. The number of channels can range
1152 * from 1 to the maximum supported by the device.
1153 *
1154 * Aspect BufferSettings: If framesPerBuffer != paFramesPerBufferUnspecified the number of frames per callback
1155 * must reflect this, in addition the host latency per device should approximate the corresponding
1156 * suggestedLatency. Based on these constraints we need to determine a number of frames per host buffer that
1157 * both capture and playback can agree on (they can be different devices), the buffer processor can adapt
1158 * between host and user buffer size, but the ratio should preferably be integral.
1159 */
1160 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
1161 PaStream** s,
1162 const PaStreamParameters *inputParameters,
1163 const PaStreamParameters *outputParameters,
1164 double sampleRate,
1165 unsigned long framesPerBuffer,
1166 PaStreamFlags streamFlags,
1167 PaStreamCallback *streamCallback,
1168 void *userData )
1169 {
1170 PaError result = paNoError;
1171 PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
1172 PaOssStream *stream = NULL;
1173 int inputChannelCount = 0, outputChannelCount = 0;
1174 PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0, inputHostFormat = 0, outputHostFormat = 0;
1175 const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0;
1176 int bpInitialized = 0;
1177 double inLatency, outLatency;
1178
1179 /* validate platform specific flags */
1180 if( (streamFlags & paPlatformSpecificFlags) != 0 )
1181 return paInvalidFlag; /* unexpected platform specific flag */
1182
1183 if( inputParameters )
1184 {
1185 /* unless alternate device specification is supported, reject the use of
1186 paUseHostApiSpecificDeviceSpecification */
1187 inputDeviceInfo = hostApi->deviceInfos[inputParameters->device];
1188 PA_ENSURE( ValidateParameters( inputParameters, inputDeviceInfo, StreamMode_In ) );
1189
1190 inputChannelCount = inputParameters->channelCount;
1191 inputSampleFormat = inputParameters->sampleFormat;
1192 }
1193 if( outputParameters )
1194 {
1195 outputDeviceInfo = hostApi->deviceInfos[outputParameters->device];
1196 PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) );
1197
1198 outputChannelCount = outputParameters->channelCount;
1199 outputSampleFormat = outputParameters->sampleFormat;
1200 }
1201
1202 /* Aspect StreamChannels: We currently demand that number of input and output channels are the same, if the same
1203 * device is opened for both directions
1204 */
1205 if( inputChannelCount > 0 && outputChannelCount > 0 )
1206 {
1207 if( inputParameters->device == outputParameters->device )
1208 {
1209 if( inputParameters->channelCount != outputParameters->channelCount )
1210 return paInvalidChannelCount;
1211 }
1212 }
1213
1214 /* allocate and do basic initialization of the stream structure */
1215 PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory );
1216 PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) );
1217
1218 PA_ENSURE( PaOssStream_Configure( stream, sampleRate, framesPerBuffer, &inLatency, &outLatency ) );
1219
1220 PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
1221
1222 if( inputParameters )
1223 {
1224 inputHostFormat = stream->capture->hostFormat;
1225 stream->streamRepresentation.streamInfo.inputLatency = inLatency +
1226 PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor ) / sampleRate;
1227 }
1228 if( outputParameters )
1229 {
1230 outputHostFormat = stream->playback->hostFormat;
1231 stream->streamRepresentation.streamInfo.outputLatency = outLatency +
1232 PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor ) / sampleRate;
1233 }
1234
1235 /* Initialize buffer processor with fixed host buffer size.
1236 * Aspect StreamSampleFormat: Here we commit the user and host sample formats, PA infrastructure will
1237 * convert between the two.
1238 */
1239 PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
1240 inputChannelCount, inputSampleFormat, inputHostFormat, outputChannelCount, outputSampleFormat,
1241 outputHostFormat, sampleRate, streamFlags, framesPerBuffer, stream->framesPerHostBuffer,
1242 paUtilFixedHostBufferSize, streamCallback, userData ) );
1243 bpInitialized = 1;
1244
1245 *s = (PaStream*)stream;
1246
1247 return result;
1248
1249 error:
1250 if( bpInitialized )
1251 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
1252 if( stream )
1253 PaOssStream_Terminate( stream );
1254
1255 return result;
1256 }
1257
1258 /*! Poll on I/O filedescriptors.
1259
1260 Poll till we've determined there's data for read or write. In the full-duplex case,
1261 we don't want to hang around forever waiting for either input or output frames, so
1262 whenever we have a timed out filedescriptor we check if we're nearing under/overrun
1263 for the other direction (critical limit set at one buffer). If so, we exit the waiting
1264 state, and go on with what we got. We align the number of frames on a host buffer
1265 boundary because it is possible that the buffer size differs for the two directions and
1266 the host buffer size is a compromise between the two.
1267 */
1268 static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *frames )
1269 {
1270 PaError result = paNoError;
1271 int pollPlayback = 0, pollCapture = 0;
1272 int captureAvail = INT_MAX, playbackAvail = INT_MAX, commonAvail;
1273 audio_buf_info bufInfo;
1274 /* int ofs = 0, nfds = stream->nfds; */
1275 fd_set readFds, writeFds;
1276 int nfds = 0;
1277 struct timeval selectTimeval = {0, 0};
1278 unsigned long timeout = stream->pollTimeout; /* In usecs */
1279 int captureFd = -1, playbackFd = -1;
1280
1281 assert( stream );
1282 assert( frames );
1283
1284 if( stream->capture )
1285 {
1286 pollCapture = 1;
1287 captureFd = stream->capture->fd;
1288 /* stream->capture->pfd->events = POLLIN; */
1289 }
1290 if( stream->playback )
1291 {
1292 pollPlayback = 1;
1293 playbackFd = stream->playback->fd;
1294 /* stream->playback->pfd->events = POLLOUT; */
1295 }
1296
1297 FD_ZERO( &readFds );
1298 FD_ZERO( &writeFds );
1299
1300 while( pollPlayback || pollCapture )
1301 {
1302 pthread_testcancel();
1303
1304 /* select may modify the timeout parameter */
1305 selectTimeval.tv_usec = timeout;
1306 nfds = 0;
1307
1308 if( pollCapture )
1309 {
1310 FD_SET( captureFd, &readFds );
1311 nfds = captureFd + 1;
1312 }
1313 if( pollPlayback )
1314 {
1315 FD_SET( playbackFd, &writeFds );
1316 nfds = PA_MAX( nfds, playbackFd + 1 );
1317 }
1318 ENSURE_( select( nfds, &readFds, &writeFds, NULL, &selectTimeval ), paUnanticipatedHostError );
1319 /*
1320 if( poll( stream->pfds + ofs, nfds, stream->pollTimeout ) < 0 )
1321 {
1322
1323 ENSURE_( -1, paUnanticipatedHostError );
1324 }
1325 */
1326 pthread_testcancel();
1327
1328 if( pollCapture )
1329 {
1330 if( FD_ISSET( captureFd, &readFds ) )
1331 {
1332 FD_CLR( captureFd, &readFds );
1333 pollCapture = 0;
1334 }
1335 /*
1336 if( stream->capture->pfd->revents & POLLIN )
1337 {
1338 --nfds;
1339 ++ofs;
1340 pollCapture = 0;
1341 }
1342 */
1343 else if( stream->playback ) /* Timed out, go on with playback? */
1344 {
1345 /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n",
1346 __FUNCTION__, stream->pollTimeout ));*/
1347 }
1348 }
1349 if( pollPlayback )
1350 {
1351 if( FD_ISSET( playbackFd, &writeFds ) )
1352 {
1353 FD_CLR( playbackFd, &writeFds );
1354 pollPlayback = 0;
1355 }
1356 /*
1357 if( stream->playback->pfd->revents & POLLOUT )
1358 {
1359 --nfds;
1360 pollPlayback = 0;
1361 }
1362 */
1363 else if( stream->capture ) /* Timed out, go on with capture? */
1364 {
1365 /*PA_DEBUG(( "%s: Trying to poll again for playback frames, pollTimeout: %d\n\n",
1366 __FUNCTION__, stream->pollTimeout ));*/
1367 }
1368 }
1369 }
1370
1371 if( stream->capture )
1372 {
1373 ENSURE_( ioctl( captureFd, SNDCTL_DSP_GETISPACE, &bufInfo ), paUnanticipatedHostError );
1374 captureAvail = bufInfo.fragments * stream->capture->hostFrames;
1375 if( !captureAvail )
1376 PA_DEBUG(( "%s: captureAvail: 0\n", __FUNCTION__ ));
1377
1378 captureAvail = captureAvail == 0 ? INT_MAX : captureAvail; /* Disregard if zero */
1379 }
1380 if( stream->playback )
1381 {
1382 ENSURE_( ioctl( playbackFd, SNDCTL_DSP_GETOSPACE, &bufInfo ), paUnanticipatedHostError );
1383 playbackAvail = bufInfo.fragments * stream->playback->hostFrames;
1384 if( !playbackAvail )
1385 {
1386 PA_DEBUG(( "%s: playbackAvail: 0\n", __FUNCTION__ ));
1387 }
1388
1389 playbackAvail = playbackAvail == 0 ? INT_MAX : playbackAvail; /* Disregard if zero */
1390 }
1391
1392 commonAvail = PA_MIN( captureAvail, playbackAvail );
1393 if( commonAvail == INT_MAX )
1394 commonAvail = 0;
1395 commonAvail -= commonAvail % stream->framesPerHostBuffer;
1396
1397 assert( commonAvail != INT_MAX );
1398 assert( commonAvail >= 0 );
1399 *frames = commonAvail;
1400
1401 error:
1402 return result;
1403 }
1404
1405 /** Prepare stream for capture/playback.
1406 *
1407 * In order to synchronize capture and playback properly we use the SETTRIGGER command.
1408 */
1409 static PaError PaOssStream_Prepare( PaOssStream *stream )
1410 {
1411 PaError result = paNoError;
1412 int enableBits = 0;
1413
1414 if( stream->triggered )
1415 return result;
1416
1417 if( stream->playback )
1418 {
1419 size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback );
1420 memset( stream->playback->buffer, 0, bufSz );
1421
1422 /* Looks like we have to turn off blocking before we try this, but if we don't fill the buffer
1423 * OSS will complain. */
1424 PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
1425 while (1)
1426 {
1427 if( write( stream->playback->fd, stream->playback->buffer, bufSz ) < 0 )
1428 break;
1429 }
1430 PA_ENSURE( ModifyBlocking( stream->playback->fd, 1 ) );
1431 }
1432
1433 if( stream->sharedDevice )
1434 {
1435 enableBits = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
1436 ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
1437 }
1438 else
1439 {
1440 if( stream->capture )
1441 {
1442 enableBits = PCM_ENABLE_INPUT;
1443 ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
1444 }
1445 if( stream->playback )
1446 {
1447 enableBits = PCM_ENABLE_OUTPUT;
1448 ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
1449 }
1450 }
1451
1452 /* Ok, we have triggered the stream */
1453 stream->triggered = 1;
1454
1455 error:
1456 return result;
1457 }
1458
1459 /** Stop audio processing
1460 *
1461 */
1462 static PaError PaOssStream_Stop( PaOssStream *stream, int abort )
1463 {
1464 PaError result = paNoError;
1465
1466 /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST.
1467 * Also disable capture/playback till the stream is started again */
1468 if( stream->capture )
1469 {
1470 ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );
1471 }
1472 if( stream->playback && !stream->sharedDevice )
1473 {
1474 ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );
1475 }
1476
1477 error:
1478 return result;
1479 }
1480
1481 /** Clean up after thread exit.
1482 *
1483 * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here
1484 */
1485 static void OnExit( void *data )
1486 {
1487 PaOssStream *stream = (PaOssStream *) data;
1488 assert( data );
1489
1490 PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
1491
1492 PaOssStream_Stop( stream, stream->callbackAbort );
1493
1494 PA_DEBUG(( "OnExit: Stoppage\n" ));
1495
1496 /* Eventually notify user all buffers have played */
1497 if( stream->streamRepresentation.streamFinishedCallback )
1498 stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
1499
1500 stream->callbackAbort = 0; /* Clear state */
1501 stream->isActive = 0;
1502 }
1503
1504 static PaError SetUpBuffers( PaOssStream *stream, unsigned long framesAvail )
1505 {
1506 PaError result = paNoError;
1507
1508 if( stream->capture )
1509 {
1510 PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer,
1511 stream->capture->hostChannelCount );
1512 PaUtil_SetInputFrameCount( &stream->bufferProcessor, framesAvail );
1513 }
1514 if( stream->playback )
1515 {
1516 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer,
1517 stream->playback->hostChannelCount );
1518 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, framesAvail );
1519 }
1520
1521 return result;
1522 }
1523
1524 /** Thread procedure for callback processing.
1525 *
1526 * Aspect StreamState: StartStream will wait on this to initiate audio processing, useful in case the
1527 * callback should be used for buffer priming. When the stream is cancelled a separate function will
1528 * take care of the transition to the Callback Finished state (the stream isn't considered Stopped
1529 * before StopStream() or AbortStream() are called).
1530 */
1531 static void *PaOSS_AudioThreadProc( void *userData )
1532 {
1533 PaError result = paNoError;
1534 PaOssStream *stream = (PaOssStream*)userData;
1535 unsigned long framesAvail, framesProcessed;
1536 int callbackResult = paContinue;
1537 int triggered = stream->triggered; /* See if SNDCTL_DSP_TRIGGER has been issued already */
1538 int initiateProcessing = triggered; /* Already triggered? */
1539 PaStreamCallbackFlags cbFlags = 0; /* We might want to keep state across iterations */
1540 PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* TODO: IMPLEMENT ME */
1541
1542 /*
1543 #if ( SOUND_VERSION > 0x030904 )
1544 audio_errinfo errinfo;
1545 #endif
1546 */
1547
1548 assert( stream );
1549
1550 pthread_cleanup_push( &OnExit, stream ); /* Execute OnExit when exiting */
1551
1552 /* The first time the stream is started we use SNDCTL_DSP_TRIGGER to accurately start capture and
1553 * playback in sync, when the stream is restarted after being stopped we simply start by reading/
1554 * writing.
1555 */
1556 PA_ENSURE( PaOssStream_Prepare( stream ) );
1557
1558 /* If we are to initiate processing implicitly by reading/writing data, we start off in blocking mode */
1559 if( initiateProcessing )
1560 {
1561 /* Make sure devices are in blocking mode */
1562 if( stream->capture )
1563 ModifyBlocking( stream->capture->fd, 1 );
1564 if( stream->playback )
1565 ModifyBlocking( stream->playback->fd, 1 );
1566 }
1567
1568 while( 1 )
1569 {
1570 pthread_testcancel();
1571
1572 if( stream->callbackStop && callbackResult == paContinue )
1573 {
1574 PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
1575 callbackResult = paComplete;
1576 }
1577
1578 /* Aspect StreamState: Because of the messy OSS scheme we can't explicitly trigger device start unless
1579 * the stream has been recently started, we will have to go right ahead and read/write in blocking
1580 * fashion to trigger operation. Therefore we begin with processing one host buffer before we switch
1581 * to non-blocking mode.
1582 */
1583 if( !initiateProcessing )
1584 {
1585 PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) ); /* Wait on available frames */
1586 assert( framesAvail % stream->framesPerHostBuffer == 0 );
1587 }
1588 else
1589 {
1590 framesAvail = stream->framesPerHostBuffer;
1591 }
1592
1593 while( framesAvail > 0 )
1594 {
1595 unsigned long frames = framesAvail;
1596
1597 pthread_testcancel();
1598
1599 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
1600
1601 /* Read data */
1602 if ( stream->capture )
1603 {
1604 PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) );
1605 assert( frames == framesAvail );
1606 }
1607
1608 #if ( SOUND_VERSION >= 0x030904 )
1609 /*
1610 Check with OSS to see if there have been any under/overruns
1611 since last time we checked.
1612 */
1613 /*
1614 if( ioctl( stream->deviceHandle, SNDCTL_DSP_GETERROR, &errinfo ) >= 0 )
1615 {
1616 if( errinfo.play_underruns )
1617 cbFlags |= paOutputUnderflow ;
1618 if( errinfo.record_underruns )
1619 cbFlags |= paInputUnderflow ;
1620 }
1621 else
1622 PA_DEBUG(( "SNDCTL_DSP_GETERROR command failed: %s\n", strerror( errno ) ));
1623 */
1624 #endif
1625
1626 PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
1627 cbFlags );
1628 cbFlags = 0;
1629 PA_ENSURE( SetUpBuffers( stream, framesAvail ) );
1630
1631 framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
1632 &callbackResult );
1633 assert( framesProcessed == framesAvail );
1634 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
1635
1636 if ( stream->playback )
1637 {
1638 frames = framesAvail;
1639
1640 PA_ENSURE( PaOssStreamComponent_Write( stream->playback, &frames ) );
1641 assert( frames == framesAvail );
1642
1643 /* TODO: handle bytesWritten != bytesRequested (slippage?) */
1644 }
1645
1646 framesAvail -= framesProcessed;
1647 stream->framesProcessed += framesProcessed;
1648
1649 if( callbackResult != paContinue )
1650 break;
1651 }
1652
1653 if( initiateProcessing || !triggered )
1654 {
1655 /* Non-blocking */
1656 if( stream->capture )
1657 PA_ENSURE( ModifyBlocking( stream->capture->fd, 0 ) );
1658 if( stream->playback && !stream->sharedDevice )
1659 PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
1660
1661 initiateProcessing = 0;
1662 sem_post( &stream->semaphore );
1663 }
1664
1665 if( callbackResult != paContinue )
1666 {
1667 stream->callbackAbort = callbackResult == paAbort;
1668 if( stream->callbackAbort || PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
1669 break;
1670 }
1671 }
1672
1673 pthread_cleanup_pop( 1 );
1674
1675 error:
1676 pthread_exit( NULL );
1677 }
1678
1679 /** Close the stream.
1680 *
1681 */
1682 static PaError CloseStream( PaStream* s )
1683 {
1684 PaError result = paNoError;
1685 PaOssStream *stream = (PaOssStream*)s;
1686
1687 assert( stream );
1688
1689 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
1690 PaOssStream_Terminate( stream );
1691
1692 return result;
1693 }
1694
1695 /** Start the stream.
1696 *
1697 * Aspect StreamState: After returning, the stream shall be in the Active state, implying that an eventual
1698 * callback will be repeatedly called in a separate thread. If a separate thread is started this function
1699 * will block untill it has started processing audio, otherwise audio processing is started directly.
1700 */
1701 static PaError StartStream( PaStream *s )
1702 {
1703 PaError result = paNoError;
1704 PaOssStream *stream = (PaOssStream*)s;
1705
1706 stream->isActive = 1;
1707 stream->isStopped = 0;
1708 stream->lastPosPtr = 0;
1709 stream->lastStreamBytes = 0;
1710 stream->framesProcessed = 0;
1711
1712 /* only use the thread for callback streams */
1713 if( stream->bufferProcessor.streamCallback )
1714 {
1715 PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) );
1716 sem_wait( &stream->semaphore );
1717 }
1718 else
1719 PA_ENSURE( PaOssStream_Prepare( stream ) );
1720
1721 error:
1722 return result;
1723 }
1724
1725 static PaError RealStop( PaOssStream *stream, int abort )
1726 {
1727 PaError result = paNoError;
1728
1729 if( stream->callbackMode )
1730 {
1731 if( abort )
1732 stream->callbackAbort = 1;
1733 else
1734 stream->callbackStop = 1;
1735
1736 PA_ENSURE( PaUtil_CancelThreading( &stream->threading, !abort, NULL ) );
1737
1738 stream->callbackStop = stream->callbackAbort = 0;
1739 }
1740 else
1741 PA_ENSURE( PaOssStream_Stop( stream, abort ) );
1742
1743 stream->isStopped = 1;
1744
1745 error:
1746 return result;
1747 }
1748
1749 /** Stop the stream.
1750 *
1751 * Aspect StreamState: This will cause the stream to transition to the Stopped state, playing all enqueued
1752 * buffers.
1753 */
1754 static PaError StopStream( PaStream *s )
1755 {
1756 return RealStop( (PaOssStream *)s, 0 );
1757 }
1758
1759 /** Abort the stream.
1760 *
1761 * Aspect StreamState: This will cause the stream to transition to the Stopped state, discarding all enqueued
1762 * buffers. Note that the buffers are not currently correctly discarded, this is difficult without closing
1763 * the OSS device.
1764 */
1765 static PaError AbortStream( PaStream *s )
1766 {
1767 return RealStop( (PaOssStream *)s, 1 );
1768 }
1769
1770 /** Is the stream in the Stopped state.
1771 *
1772 */
1773 static PaError IsStreamStopped( PaStream *s )
1774 {
1775 PaOssStream *stream = (PaOssStream*)s;
1776
1777 return (stream->isStopped);
1778 }
1779
1780 /** Is the stream in the Active state.
1781 *
1782 */
1783 static PaError IsStreamActive( PaStream *s )
1784 {
1785 PaOssStream *stream = (PaOssStream*)s;
1786
1787 return (stream->isActive);
1788 }
1789
1790 static PaTime GetStreamTime( PaStream *s )
1791 {
1792 PaOssStream *stream = (PaOssStream*)s;
1793 count_info info;
1794 int delta;
1795
1796 if( stream->playback ) {
1797 if( ioctl( stream->playback->fd, SNDCTL_DSP_GETOPTR, &info) == 0 ) {
1798 delta = ( info.bytes - stream->lastPosPtr ) /* & 0x000FFFFF*/;
1799 return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->playback ) / stream->sampleRate;
1800 }
1801 }
1802 else {
1803 if (ioctl( stream->capture->fd, SNDCTL_DSP_GETIPTR, &info) == 0) {
1804 delta = (info.bytes - stream->lastPosPtr) /*& 0x000FFFFF*/;
1805 return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->capture ) / stream->sampleRate;
1806 }
1807 }
1808
1809 /* the ioctl failed, but we can still give a coarse estimate */
1810
1811 return stream->framesProcessed / stream->sampleRate;
1812 }
1813
1814
1815 static double GetStreamCpuLoad( PaStream* s )
1816 {
1817 PaOssStream *stream = (PaOssStream*)s;
1818
1819 return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
1820 }
1821
1822
1823 /*
1824 As separate stream interfaces are used for blocking and callback
1825 streams, the following functions can be guaranteed to only be called
1826 for blocking streams.
1827 */
1828
1829
1830 static PaError ReadStream( PaStream* s,
1831 void *buffer,
1832 unsigned long frames )
1833 {
1834 PaOssStream *stream = (PaOssStream*)s;
1835 int bytesRequested, bytesRead;
1836 unsigned long framesRequested;
1837 void *userBuffer;
1838
1839 /* If user input is non-interleaved, PaUtil_CopyInput will manipulate the channel pointers,
1840 * so we copy the user provided pointers */
1841 if( stream->bufferProcessor.userInputIsInterleaved )
1842 userBuffer = buffer;
1843 else /* Copy channels into local array */
1844 {
1845 userBuffer = stream->capture->userBuffers;
1846 memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->capture->userChannelCount );
1847 }
1848
1849 while( frames )
1850 {
1851 framesRequested = PA_MIN( frames, stream->capture->hostFrames );
1852
1853 bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture );
1854 bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested );
1855 if ( bytesRequested != bytesRead )
1856 return paUnanticipatedHostError;
1857
1858 PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames );
1859 PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount );
1860 PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested );
1861 frames -= framesRequested;
1862 }
1863 return paNoError;
1864 }
1865
1866
1867 static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames )
1868 {
1869 PaOssStream *stream = (PaOssStream*)s;
1870 int bytesRequested, bytesWritten;
1871 unsigned long framesConverted;
1872 const void *userBuffer;
1873
1874 /* If user output is non-interleaved, PaUtil_CopyOutput will manipulate the channel pointers,
1875 * so we copy the user provided pointers */
1876 if( stream->bufferProcessor.userOutputIsInterleaved )
1877 userBuffer = buffer;
1878 else
1879 {
1880 /* Copy channels into local array */
1881 userBuffer = stream->playback->userBuffers;
1882 memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback->userChannelCount );
1883 }
1884
1885 while( frames )
1886 {
1887 PaUtil_SetOutputFrameCount( &stream->bufferProcessor, stream->playback->hostFrames );
1888 PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, stream->playback->hostChannelCount );
1889
1890 framesConverted = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames );
1891 frames -= framesConverted;
1892
1893 bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback );
1894 bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested );
1895
1896 if ( bytesRequested != bytesWritten )
1897 return paUnanticipatedHostError;
1898 }
1899 return paNoError;
1900 }
1901
1902
1903 static signed long GetStreamReadAvailable( PaStream* s )
1904 {
1905 PaOssStream *stream = (PaOssStream*)s;
1906 audio_buf_info info;
1907
1908 if( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ) < 0 )
1909 return paUnanticipatedHostError;
1910 return info.fragments * stream->capture->hostFrames;
1911 }
1912
1913
1914 /* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */
1915 static signed long GetStreamWriteAvailable( PaStream* s )
1916 {
1917 PaOssStream *stream = (PaOssStream*)s;
1918 int delay = 0;
1919
1920 if( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ) < 0 )
1921 return paUnanticipatedHostError;
1922
1923 return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );
1924 }
1925