Debian Codegraph @

external/portaudio/pa_mac_core_blocking.c

raw symbols SCIP
1 /*
2 * Implementation of the PortAudio API for Apple AUHAL
3 *
4 * PortAudio Portable Real-Time Audio Library
5 * Latest Version at: http://www.portaudio.com
6 *
7 * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
8 * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
9 *
10 * Dominic's code was based on code by Phil Burk, Darren Gibbs,
11 * Gord Peters, Stephane Letz, and Greg Pfiel.
12 *
13 * The following people also deserve acknowledgements:
14 *
15 * Olivier Tristan for feedback and testing
16 * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
17 * interface.
18 *
19 *
20 * Based on the Open Source API proposed by Ross Bencina
21 * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining
24 * a copy of this software and associated documentation files
25 * (the "Software"), to deal in the Software without restriction,
26 * including without limitation the rights to use, copy, modify, merge,
27 * publish, distribute, sublicense, and/or sell copies of the Software,
28 * and to permit persons to whom the Software is furnished to do so,
29 * subject to the following conditions:
30 *
31 * The above copyright notice and this permission notice shall be
32 * included in all copies or substantial portions of the Software.
33 *
34 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
35 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
36 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
37 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
38 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
39 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
40 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
41 */
42
43 /*
44 * The text above constitutes the entire PortAudio license; however,
45 * the PortAudio community also makes the following non-binding requests:
46 *
47 * Any person wishing to distribute modifications to the Software is
48 * requested to send the modifications to the original developer so that
49 * they can be incorporated into the canonical version. It is also
50 * requested that these non-binding requests be included along with the
51 * license above.
52 */
53
54 /**
55 @file
56 @ingroup hostapi_src
57
58 This file contains the implementation
59 required for blocking I/O. It is separated from pa_mac_core.c simply to ease
60 development.
61 */
62
63 #include "pa_mac_core_blocking.h"
64 #include "pa_mac_core_internal.h"
65 #include <assert.h>
66 #ifdef MOSX_USE_NON_ATOMIC_FLAG_BITS
67 # define OSAtomicOr32( a, b ) ( (*(b)) |= (a) )
68 # define OSAtomicAnd32( a, b ) ( (*(b)) &= (a) )
69 #else
70 # include <libkern/OSAtomic.h>
71 #endif
72
73 /*
74 * This function determines the size of a particular sample format.
75 * if the format is not recognized, this returns zero.
76 */
77 static size_t computeSampleSizeFromFormat( PaSampleFormat format )
78 {
79 switch( format & (~paNonInterleaved) ) {
80 case paFloat32: return 4;
81 case paInt32: return 4;
82 case paInt24: return 3;
83 case paInt16: return 2;
84 case paInt8:
85 case paUInt8: return 1;
86 default: return 0;
87 }
88 }
89
90 /*
91 * Same as computeSampleSizeFromFormat, except that if
92 * the size is not a power of two, it returns the next power of two up
93 */
94 static size_t computeSampleSizeFromFormatPow2( PaSampleFormat format )
95 {
96 switch( format & (~paNonInterleaved) ) {
97 case paFloat32: return 4;
98 case paInt32: return 4;
99 case paInt24: return 4;
100 case paInt16: return 2;
101 case paInt8:
102 case paUInt8: return 1;
103 default: return 0;
104 }
105 }
106
107
108 /*
109 * Functions for initializing, resetting, and destroying BLIO structures.
110 *
111 */
112
113 /**
114 * This should be called with the relevant info when initializing a stream for callback.
115 *
116 * @param ringBufferSizeInFrames must be a power of 2
117 */
118 PaError initializeBlioRingBuffers(
119 PaMacBlio *blio,
120 PaSampleFormat inputSampleFormat,
121 PaSampleFormat outputSampleFormat,
122 long ringBufferSizeInFrames,
123 int inChan,
124 int outChan )
125 {
126 void *data;
127 int result;
128 OSStatus err;
129
130 /* zeroify things */
131 bzero( blio, sizeof( PaMacBlio ) );
132 /* this is redundant, but the buffers are used to check
133 if the buffers have been initialized, so we do it explicitly. */
134 blio->inputRingBuffer.buffer = NULL;
135 blio->outputRingBuffer.buffer = NULL;
136
137 /* initialize simple data */
138 blio->ringBufferFrames = ringBufferSizeInFrames;
139 blio->inputSampleFormat = inputSampleFormat;
140 blio->inputSampleSizeActual = computeSampleSizeFromFormat(inputSampleFormat);
141 blio->inputSampleSizePow2 = computeSampleSizeFromFormatPow2(inputSampleFormat); // FIXME: WHY?
142 blio->outputSampleFormat = outputSampleFormat;
143 blio->outputSampleSizeActual = computeSampleSizeFromFormat(outputSampleFormat);
144 blio->outputSampleSizePow2 = computeSampleSizeFromFormatPow2(outputSampleFormat);
145
146 blio->inChan = inChan;
147 blio->outChan = outChan;
148 blio->statusFlags = 0;
149 blio->errors = paNoError;
150 #ifdef PA_MAC_BLIO_MUTEX
151 blio->isInputEmpty = false;
152 blio->isOutputFull = false;
153 #endif
154
155 /* setup ring buffers */
156 #ifdef PA_MAC_BLIO_MUTEX
157 result = PaMacCore_SetUnixError( pthread_mutex_init(&(blio->inputMutex),NULL), 0 );
158 if( result )
159 goto error;
160 result = UNIX_ERR( pthread_cond_init( &(blio->inputCond), NULL ) );
161 if( result )
162 goto error;
163 result = UNIX_ERR( pthread_mutex_init(&(blio->outputMutex),NULL) );
164 if( result )
165 goto error;
166 result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) );
167 #endif
168 if( inChan ) {
169 data = calloc( ringBufferSizeInFrames, blio->inputSampleSizePow2 * inChan );
170 if( !data )
171 {
172 result = paInsufficientMemory;
173 goto error;
174 }
175
176 err = PaUtil_InitializeRingBuffer(
177 &blio->inputRingBuffer,
178 blio->inputSampleSizePow2 * inChan,
179 ringBufferSizeInFrames,
180 data );
181 assert( !err );
182 }
183 if( outChan ) {
184 data = calloc( ringBufferSizeInFrames, blio->outputSampleSizePow2 * outChan );
185 if( !data )
186 {
187 result = paInsufficientMemory;
188 goto error;
189 }
190
191 err = PaUtil_InitializeRingBuffer(
192 &blio->outputRingBuffer,
193 blio->outputSampleSizePow2 * outChan,
194 ringBufferSizeInFrames,
195 data );
196 assert( !err );
197 }
198
199 result = resetBlioRingBuffers( blio );
200 if( result )
201 goto error;
202
203 return 0;
204
205 error:
206 destroyBlioRingBuffers( blio );
207 return result;
208 }
209
210 #ifdef PA_MAC_BLIO_MUTEX
211 PaError blioSetIsInputEmpty( PaMacBlio *blio, bool isEmpty )
212 {
213 PaError result = paNoError;
214 if( isEmpty == blio->isInputEmpty )
215 goto done;
216
217 /* we need to update the value. Here's what we do:
218 * - Lock the mutex, so no one else can write.
219 * - update the value.
220 * - unlock.
221 * - broadcast to all listeners.
222 */
223 result = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
224 if( result )
225 goto done;
226 blio->isInputEmpty = isEmpty;
227 result = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
228 if( result )
229 goto done;
230 result = UNIX_ERR( pthread_cond_broadcast( &blio->inputCond ) );
231 if( result )
232 goto done;
233
234 done:
235 return result;
236 }
237 PaError blioSetIsOutputFull( PaMacBlio *blio, bool isFull )
238 {
239 PaError result = paNoError;
240 if( isFull == blio->isOutputFull )
241 goto done;
242
243 /* we need to update the value. Here's what we do:
244 * - Lock the mutex, so no one else can write.
245 * - update the value.
246 * - unlock.
247 * - broadcast to all listeners.
248 */
249 result = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
250 if( result )
251 goto done;
252 blio->isOutputFull = isFull;
253 result = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
254 if( result )
255 goto done;
256 result = UNIX_ERR( pthread_cond_broadcast( &blio->outputCond ) );
257 if( result )
258 goto done;
259
260 done:
261 return result;
262 }
263 #endif
264
265 /* This should be called after stopping or aborting the stream, so that on next
266 start, the buffers will be ready. */
267 PaError resetBlioRingBuffers( PaMacBlio *blio )
268 {
269 #ifdef PA_MAC__BLIO_MUTEX
270 int result;
271 #endif
272 blio->statusFlags = 0;
273 if( blio->outputRingBuffer.buffer ) {
274 PaUtil_FlushRingBuffer( &blio->outputRingBuffer );
275 /* Fill the buffer with zeros. */
276 bzero( blio->outputRingBuffer.buffer,
277 blio->outputRingBuffer.bufferSize * blio->outputRingBuffer.elementSizeBytes );
278 PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->ringBufferFrames );
279
280 /* Update isOutputFull. */
281 #ifdef PA_MAC__BLIO_MUTEX
282 result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize );
283 if( result )
284 goto error;
285 #endif
286 /*
287 printf( "------%d\n" , blio->outChan );
288 printf( "------%d\n" , blio->outputSampleSize );
289 */
290 }
291 if( blio->inputRingBuffer.buffer ) {
292 PaUtil_FlushRingBuffer( &blio->inputRingBuffer );
293 bzero( blio->inputRingBuffer.buffer,
294 blio->inputRingBuffer.bufferSize * blio->inputRingBuffer.elementSizeBytes );
295 /* Update isInputEmpty. */
296 #ifdef PA_MAC__BLIO_MUTEX
297 result = blioSetIsInputEmpty( blio, true );
298 if( result )
299 goto error;
300 #endif
301 }
302 return paNoError;
303 #ifdef PA_MAC__BLIO_MUTEX
304 error:
305 return result;
306 #endif
307 }
308
309 /*This should be called when you are done with the blio. It can safely be called
310 multiple times if there are no exceptions. */
311 PaError destroyBlioRingBuffers( PaMacBlio *blio )
312 {
313 PaError result = paNoError;
314 if( blio->inputRingBuffer.buffer ) {
315 free( blio->inputRingBuffer.buffer );
316 #ifdef PA_MAC__BLIO_MUTEX
317 result = UNIX_ERR( pthread_mutex_destroy( & blio->inputMutex ) );
318 if( result ) return result;
319 result = UNIX_ERR( pthread_cond_destroy( & blio->inputCond ) );
320 if( result ) return result;
321 #endif
322 }
323 blio->inputRingBuffer.buffer = NULL;
324 if( blio->outputRingBuffer.buffer ) {
325 free( blio->outputRingBuffer.buffer );
326 #ifdef PA_MAC__BLIO_MUTEX
327 result = UNIX_ERR( pthread_mutex_destroy( & blio->outputMutex ) );
328 if( result ) return result;
329 result = UNIX_ERR( pthread_cond_destroy( & blio->outputCond ) );
330 if( result ) return result;
331 #endif
332 }
333 blio->outputRingBuffer.buffer = NULL;
334
335 return result;
336 }
337
338 /*
339 * this is the BlioCallback function. It expects to receive a PaMacBlio Object
340 * pointer as userData.
341 *
342 */
343 int BlioCallback( const void *input, void *output, unsigned long frameCount,
344 const PaStreamCallbackTimeInfo* timeInfo,
345 PaStreamCallbackFlags statusFlags,
346 void *userData )
347 {
348 PaMacBlio *blio = (PaMacBlio*)userData;
349 ring_buffer_size_t framesAvailable;
350 ring_buffer_size_t framesToTransfer;
351 ring_buffer_size_t framesTransferred;
352
353 /* set flags returned by OS: */
354 OSAtomicOr32( statusFlags, &blio->statusFlags ) ;
355
356 /* --- Handle Input Buffer --- */
357 if( blio->inChan ) {
358 framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer );
359
360 /* check for underflow */
361 if( framesAvailable < frameCount )
362 {
363 OSAtomicOr32( paInputOverflow, &blio->statusFlags );
364 framesToTransfer = framesAvailable;
365 }
366 else
367 {
368 framesToTransfer = (ring_buffer_size_t)frameCount;
369 }
370
371 /* Copy the data from the audio input to the application ring buffer. */
372 /*printf( "reading %d\n", toRead );*/
373 framesTransferred = PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, framesToTransfer );
374 assert( framesToTransfer == framesTransferred );
375 #ifdef PA_MAC__BLIO_MUTEX
376 /* Priority inversion. See notes below. */
377 blioSetIsInputEmpty( blio, false );
378 #endif
379 }
380
381
382 /* --- Handle Output Buffer --- */
383 if( blio->outChan ) {
384 framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
385
386 /* check for underflow */
387 if( framesAvailable < frameCount )
388 {
389 /* zero out the end of the output buffer that we do not have data for */
390 framesToTransfer = framesAvailable;
391
392 size_t bytesPerFrame = blio->outputSampleSizeActual * blio->outChan;
393 size_t offsetInBytes = framesToTransfer * bytesPerFrame;
394 size_t countInBytes = (frameCount - framesToTransfer) * bytesPerFrame;
395 bzero( ((char *)output) + offsetInBytes, countInBytes );
396
397 OSAtomicOr32( paOutputUnderflow, &blio->statusFlags );
398 framesToTransfer = framesAvailable;
399 }
400 else
401 {
402 framesToTransfer = (ring_buffer_size_t)frameCount;
403 }
404
405 /* copy the data */
406 /*printf( "writing %d\n", toWrite );*/
407 framesTransferred = PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, framesToTransfer );
408 assert( framesToTransfer == framesTransferred );
409 #ifdef PA_MAC__BLIO_MUTEX
410 /* We have a priority inversion here. However, we will only have to
411 wait if this was true and is now false, which means we've got
412 some room in the buffer.
413 Hopefully problems will be minimized. */
414 blioSetIsOutputFull( blio, false );
415 #endif
416 }
417
418 return paContinue;
419 }
420
421 PaError ReadStream( PaStream* stream,
422 void *buffer,
423 unsigned long framesRequested )
424 {
425 PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
426 char *cbuf = (char *) buffer;
427 PaError ret = paNoError;
428 VVDBUG(("ReadStream()\n"));
429
430 while( framesRequested > 0 ) {
431 ring_buffer_size_t framesAvailable;
432 ring_buffer_size_t framesToTransfer;
433 ring_buffer_size_t framesTransferred;
434 do {
435 framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );
436 /*
437 printf( "Read Buffer is %%%g full: %ld of %ld.\n",
438 100 * (float)avail / (float) blio->inputRingBuffer.bufferSize,
439 framesAvailable, blio->inputRingBuffer.bufferSize );
440 */
441 if( framesAvailable == 0 ) {
442 #ifdef PA_MAC_BLIO_MUTEX
443 /**block when empty*/
444 ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
445 if( ret )
446 return ret;
447 while( blio->isInputEmpty ) {
448 ret = UNIX_ERR( pthread_cond_wait( &blio->inputCond, &blio->inputMutex ) );
449 if( ret )
450 return ret;
451 }
452 ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
453 if( ret )
454 return ret;
455 #else
456 Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
457 #endif
458 }
459 } while( framesAvailable == 0 );
460 framesToTransfer = (ring_buffer_size_t) MIN( framesAvailable, framesRequested );
461 framesTransferred = PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, framesToTransfer );
462 cbuf += framesTransferred * blio->inputSampleSizeActual * blio->inChan;
463 framesRequested -= framesTransferred;
464
465 if( framesToTransfer == framesAvailable ) {
466 #ifdef PA_MAC_BLIO_MUTEX
467 /* we just emptied the buffer, so we need to mark it as empty. */
468 ret = blioSetIsInputEmpty( blio, true );
469 if( ret )
470 return ret;
471 /* of course, in the meantime, the callback may have put some sats
472 in, so
473 so check for that, too, to avoid a race condition. */
474 /* FIXME - this does not seem to fix any race condition. */
475 if( PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ) ) {
476 blioSetIsInputEmpty( blio, false );
477 /* FIXME - why check? ret has not been set? */
478 if( ret )
479 return ret;
480 }
481 #endif
482 }
483 }
484
485 /* Report either paNoError or paInputOverflowed. */
486 /* may also want to report other errors, but this is non-standard. */
487 /* FIXME should not clobber ret, use if(blio->statusFlags & paInputOverflow) */
488 ret = blio->statusFlags & paInputOverflow;
489
490 /* report underflow only once: */
491 if( ret ) {
492 OSAtomicAnd32( (uint32_t)(~paInputOverflow), &blio->statusFlags );
493 ret = paInputOverflowed;
494 }
495
496 return ret;
497 }
498
499
500 PaError WriteStream( PaStream* stream,
501 const void *buffer,
502 unsigned long framesRequested )
503 {
504 PaMacCoreStream *macStream = (PaMacCoreStream*)stream;
505 PaMacBlio *blio = &macStream->blio;
506 char *cbuf = (char *) buffer;
507 PaError ret = paNoError;
508 VVDBUG(("WriteStream()\n"));
509
510 while( framesRequested > 0 && macStream->state != STOPPING ) {
511 ring_buffer_size_t framesAvailable;
512 ring_buffer_size_t framesToTransfer;
513 ring_buffer_size_t framesTransferred;
514
515 do {
516 framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
517 /*
518 printf( "Write Buffer is %%%g full: %ld of %ld.\n",
519 100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize,
520 framesAvailable, blio->outputRingBuffer.bufferSize );
521 */
522 if( framesAvailable == 0 ) {
523 #ifdef PA_MAC_BLIO_MUTEX
524 /*block while full*/
525 ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
526 if( ret )
527 return ret;
528 while( blio->isOutputFull ) {
529 ret = UNIX_ERR( pthread_cond_wait( &blio->outputCond, &blio->outputMutex ) );
530 if( ret )
531 return ret;
532 }
533 ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
534 if( ret )
535 return ret;
536 #else
537 Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
538 #endif
539 }
540 } while( framesAvailable == 0 && macStream->state != STOPPING );
541
542 if( macStream->state == STOPPING )
543 {
544 break;
545 }
546
547 framesToTransfer = MIN( framesAvailable, framesRequested );
548 framesTransferred = PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, framesToTransfer );
549 cbuf += framesTransferred * blio->outputSampleSizeActual * blio->outChan;
550 framesRequested -= framesTransferred;
551
552 #ifdef PA_MAC_BLIO_MUTEX
553 if( framesToTransfer == framesAvailable ) {
554 /* we just filled up the buffer, so we need to mark it as filled. */
555 ret = blioSetIsOutputFull( blio, true );
556 if( ret )
557 return ret;
558 /* of course, in the meantime, we may have emptied the buffer, so
559 so check for that, too, to avoid a race condition. */
560 if( PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ) ) {
561 blioSetIsOutputFull( blio, false );
562 /* FIXME remove or review this code, does not fix race, ret not set! */
563 if( ret )
564 return ret;
565 }
566 }
567 #endif
568 }
569
570 if ( macStream->state == STOPPING )
571 {
572 ret = paInternalError;
573 }
574 else if (ret == paNoError )
575 {
576 /* Test for underflow. */
577 ret = blio->statusFlags & paOutputUnderflow;
578
579 /* report underflow only once: */
580 if( ret )
581 {
582 OSAtomicAnd32( (uint32_t)(~paOutputUnderflow), &blio->statusFlags );
583 ret = paOutputUnderflowed;
584 }
585 }
586
587 return ret;
588 }
589
590 /*
591 * Wait until the data in the buffer has finished playing.
592 */
593 PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate,
594 size_t framesPerBuffer )
595 {
596 PaError result = paNoError;
597 if( blio->outputRingBuffer.buffer ) {
598 ring_buffer_size_t framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
599
600 /* Calculate when we should give up waiting. To be safe wait for two extra periods. */
601 PaTime now = PaUtil_GetTime();
602 PaTime startTime = now;
603 PaTime timeoutTime = startTime + (framesLeft + (2 * framesPerBuffer)) / sampleRate;
604
605 long msecPerBuffer = 1 + (long)( 1000.0 * framesPerBuffer / sampleRate);
606 while( framesLeft > 0 && now < timeoutTime ) {
607 VDBUG(( "waitUntilBlioWriteBufferIsFlushed: framesLeft = %d, framesPerBuffer = %ld\n",
608 framesLeft, framesPerBuffer ));
609 Pa_Sleep( msecPerBuffer );
610 framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
611 now = PaUtil_GetTime();
612 }
613
614 if( framesLeft > 0 )
615 {
616 VDBUG(( "waitUntilBlioWriteBufferIsFlushed: TIMED OUT - framesLeft = %d\n", framesLeft ));
617 result = paTimedOut;
618 }
619 }
620 return result;
621 }
622
623 signed long GetStreamReadAvailable( PaStream* stream )
624 {
625 PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
626 VVDBUG(("GetStreamReadAvailable()\n"));
627
628 return PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );
629 }
630
631
632 signed long GetStreamWriteAvailable( PaStream* stream )
633 {
634 PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
635 VVDBUG(("GetStreamWriteAvailable()\n"));
636
637 return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
638 }