summaryrefslogtreecommitdiff
path: root/3rdparty/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c
blob: 0d3b18312a713faada2b20f1483c0dba6821829f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
/*
 * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
 *
 * PortAudio Portable Real-Time Audio Library
 * Latest Version at: http://www.portaudio.com
 *
 * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
 * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
 *
 * Dominic's code was based on code by Phil Burk, Darren Gibbs,
 * Gord Peters, Stephane Letz, and Greg Pfiel.
 *
 * The following people also deserve acknowledgements:
 *
 * Olivier Tristan for feedback and testing
 * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
 * interface.
 *
 *
 * Based on the Open Source API proposed by Ross Bencina
 * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * The text above constitutes the entire PortAudio license; however,
 * the PortAudio community also makes the following non-binding requests:
 *
 * Any person wishing to distribute modifications to the Software is
 * requested to send the modifications to the original developer so that
 * they can be incorporated into the canonical version. It is also
 * requested that these non-binding requests be included along with the
 * license above.
 */

/**
 @file
 @ingroup hostapi_src
*/

#include "pa_mac_core_utilities.h"
#include "pa_mac_core_internal.h"
#include <libkern/OSAtomic.h>
#include <strings.h>
#include <pthread.h>
#include <sys/time.h>

OSStatus PaMacCore_AudioHardwareGetProperty(
        AudioHardwarePropertyID inPropertyID,
        UInt32*                 ioPropertyDataSize,
        void*                   outPropertyData )
{
    AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
    return AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
}

OSStatus PaMacCore_AudioHardwareGetPropertySize(
        AudioHardwarePropertyID inPropertyID,
        UInt32*                 outSize )
{
    AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
    return AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &address, 0, NULL, outSize);
}

OSStatus PaMacCore_AudioDeviceGetProperty(
        AudioDeviceID         inDevice,
        UInt32                inChannel,
        Boolean               isInput,
        AudioDevicePropertyID inPropertyID,
        UInt32*               ioPropertyDataSize,
        void*                 outPropertyData )
{
    AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
    AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
    return AudioObjectGetPropertyData(inDevice, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
}

OSStatus PaMacCore_AudioDeviceSetProperty(
        AudioDeviceID         inDevice,
        const AudioTimeStamp* inWhen,
        UInt32                inChannel,
        Boolean               isInput,
        AudioDevicePropertyID inPropertyID,
        UInt32                inPropertyDataSize,
        const void*           inPropertyData )
{
    AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
    AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
    return AudioObjectSetPropertyData(inDevice, &address, 0, NULL, inPropertyDataSize, inPropertyData);
}

OSStatus PaMacCore_AudioDeviceGetPropertySize(
        AudioDeviceID         inDevice,
        UInt32                inChannel,
        Boolean               isInput,
        AudioDevicePropertyID inPropertyID,
        UInt32*               outSize )
{
    AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
    AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
    return AudioObjectGetPropertyDataSize(inDevice, &address, 0, NULL, outSize);
}

OSStatus PaMacCore_AudioDeviceAddPropertyListener(
        AudioDeviceID                   inDevice,
        UInt32                          inChannel,
        Boolean                         isInput,
        AudioDevicePropertyID           inPropertyID,
        AudioObjectPropertyListenerProc inProc,
        void*                           inClientData )
{
    AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
    AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
    return AudioObjectAddPropertyListener(inDevice, &address, inProc, inClientData);
}

OSStatus PaMacCore_AudioDeviceRemovePropertyListener(
        AudioDeviceID                   inDevice,
        UInt32                          inChannel,
        Boolean                         isInput,
        AudioDevicePropertyID           inPropertyID,
        AudioObjectPropertyListenerProc inProc,
        void*                           inClientData )
{
    AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
    AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
    return AudioObjectRemovePropertyListener(inDevice, &address, inProc, inClientData);
}

OSStatus PaMacCore_AudioStreamGetProperty(
        AudioStreamID         inStream,
        UInt32                inChannel,
        AudioDevicePropertyID inPropertyID,
        UInt32*               ioPropertyDataSize,
        void*                 outPropertyData )
{
    AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
    return AudioObjectGetPropertyData(inStream, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
}

PaError PaMacCore_SetUnixError( int err, int line )
{
    PaError ret;
    const char *errorText;

    if( err == 0 )
    {
        return paNoError;
    }

    ret = paNoError;
    errorText = strerror( err );

    /** Map Unix error to PaError. Pretty much the only one that maps
        is ENOMEM. */
    if( err == ENOMEM )
        ret = paInsufficientMemory;
    else
        ret = paInternalError;

    DBUG(("%d on line %d: msg='%s'\n", err, line, errorText));
    PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText );

    return ret;
}

/*
 * Translates MacOS generated errors into PaErrors
 */
PaError PaMacCore_SetError(OSStatus error, int line, int isError)
{
    /*FIXME: still need to handle possible ComponentResult values.*/
    /*       unfortunately, they don't seem to be documented anywhere.*/
    PaError result;
    const char *errorType;
    const char *errorText;

    switch (error) {
    case kAudioHardwareNoError:
        return paNoError;
    case kAudioHardwareNotRunningError:
        errorText = "Audio Hardware Not Running";
        result = paInternalError;
        break;
    case kAudioHardwareUnspecifiedError:
        errorText = "Unspecified Audio Hardware Error";
        result = paInternalError;
        break;
    case kAudioHardwareUnknownPropertyError:
        errorText = "Audio Hardware: Unknown Property";
        result = paInternalError;
        break;
    case kAudioHardwareBadPropertySizeError:
        errorText = "Audio Hardware: Bad Property Size";
        result = paInternalError;
        break;
    case kAudioHardwareIllegalOperationError:
        errorText = "Audio Hardware: Illegal Operation";
        result = paInternalError;
        break;
    case kAudioHardwareBadDeviceError:
        errorText = "Audio Hardware: Bad Device";
        result = paInvalidDevice;
        break;
    case kAudioHardwareBadStreamError:
        errorText = "Audio Hardware: BadStream";
        result = paBadStreamPtr;
        break;
    case kAudioHardwareUnsupportedOperationError:
        errorText = "Audio Hardware: Unsupported Operation";
        result = paInternalError;
        break;
    case kAudioDeviceUnsupportedFormatError:
        errorText = "Audio Device: Unsupported Format";
        result = paSampleFormatNotSupported;
        break;
    case kAudioDevicePermissionsError:
        errorText = "Audio Device: Permissions Error";
        result = paDeviceUnavailable;
        break;
    /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */
    case kAudioUnitErr_InvalidProperty:
        errorText = "Audio Unit: Invalid Property";
        result = paInternalError;
        break;
    case kAudioUnitErr_InvalidParameter:
        errorText = "Audio Unit: Invalid Parameter";
        result = paInternalError;
        break;
    case kAudioUnitErr_NoConnection:
        errorText = "Audio Unit: No Connection";
        result = paInternalError;
        break;
    case kAudioUnitErr_FailedInitialization:
        errorText = "Audio Unit: Initialization Failed";
        result = paInternalError;
        break;
    case kAudioUnitErr_TooManyFramesToProcess:
        errorText = "Audio Unit: Too Many Frames";
        result = paInternalError;
        break;
    case kAudioUnitErr_InvalidFile:
        errorText = "Audio Unit: Invalid File";
        result = paInternalError;
        break;
    case kAudioUnitErr_UnknownFileType:
        errorText = "Audio Unit: Unknown File Type";
        result = paInternalError;
        break;
    case kAudioUnitErr_FileNotSpecified:
        errorText = "Audio Unit: File Not Specified";
        result = paInternalError;
        break;
    case kAudioUnitErr_FormatNotSupported:
        errorText = "Audio Unit: Format Not Supported";
        result = paInternalError;
        break;
    case kAudioUnitErr_Uninitialized:
        errorText = "Audio Unit: Uninitialized";
        result = paInternalError;
        break;
    case kAudioUnitErr_InvalidScope:
        errorText = "Audio Unit: Invalid Scope";
        result = paInternalError;
        break;
    case kAudioUnitErr_PropertyNotWritable:
        errorText = "Audio Unit: PropertyNotWritable";
        result = paInternalError;
        break;
    case kAudioUnitErr_InvalidPropertyValue:
        errorText = "Audio Unit: Invalid Property Value";
        result = paInternalError;
        break;
    case kAudioUnitErr_PropertyNotInUse:
        errorText = "Audio Unit: Property Not In Use";
        result = paInternalError;
        break;
    case kAudioUnitErr_Initialized:
        errorText = "Audio Unit: Initialized";
        result = paInternalError;
        break;
    case kAudioUnitErr_InvalidOfflineRender:
        errorText = "Audio Unit: Invalid Offline Render";
        result = paInternalError;
        break;
    case kAudioUnitErr_Unauthorized:
        errorText = "Audio Unit: Unauthorized";
        result = paInternalError;
        break;
    case kAudioUnitErr_CannotDoInCurrentContext:
        errorText = "Audio Unit: cannot do in current context";
        result = paInternalError;
        break;
    default:
        errorText = "Unknown Error";
        result = paInternalError;
    }

    if (isError)
        errorType = "Error";
    else
        errorType = "Warning";

    char str[20];
    // see if it appears to be a 4-char-code
    *(UInt32 *)(str + 1) = CFSwapInt32HostToBig(error);
    if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4]))
    {
        str[0] = str[5] = '\'';
        str[6] = '\0';
    } else {
        // no, format it as an integer
        sprintf(str, "%d", (int)error);
    }

    DBUG(("%s on line %d: err='%s', msg=%s\n", errorType, line, str, errorText));

    PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );

    return result;
}

/*
 * This function computes an appropriate ring buffer size given
 * a requested latency (in seconds), sample rate and framesPerBuffer.
 *
 * The returned ringBufferSize is computed using the following
 * constraints:
 *   - it must be at least 4.
 *   - it must be at least 3x framesPerBuffer.
 *   - it must be at least 2x the suggestedLatency.
 *   - it must be a power of 2.
 * This function attempts to compute the minimum such size.
 *
 * FEEDBACK: too liberal/conservative/another way?
 */
long computeRingBufferSize( const PaStreamParameters *inputParameters,
                            const PaStreamParameters *outputParameters,
                            long inputFramesPerBuffer,
                            long outputFramesPerBuffer,
                            double sampleRate )
{
    long ringSize;
    int index;
    int i;
    double latency ;
    long framesPerBuffer ;

    VVDBUG(( "computeRingBufferSize()\n" ));

    assert( inputParameters || outputParameters );

    if( outputParameters && inputParameters )
    {
        latency = MAX( inputParameters->suggestedLatency, outputParameters->suggestedLatency );
        framesPerBuffer = MAX( inputFramesPerBuffer, outputFramesPerBuffer );
    }
    else if( outputParameters )
    {
        latency = outputParameters->suggestedLatency;
        framesPerBuffer = outputFramesPerBuffer ;
    }
    else /* we have inputParameters  */
    {
        latency = inputParameters->suggestedLatency;
        framesPerBuffer = inputFramesPerBuffer ;
    }

    ringSize = (long) ( latency * sampleRate * 2 + .5);
    VDBUG( ( "suggested latency : %d\n", (int) (latency*sampleRate) ) );
    if( ringSize < framesPerBuffer * 3 )
        ringSize = framesPerBuffer * 3 ;
    VDBUG(("framesPerBuffer:%d\n",(int)framesPerBuffer));
    VDBUG(("Ringbuffer size (1): %d\n", (int)ringSize ));

    /* make sure it's at least 4 */
    ringSize = MAX( ringSize, 4 );

    /* round up to the next power of 2 */
    index = -1;
    for( i=0; i<sizeof(long)*8; ++i )
        if( ringSize >> i & 0x01 )
            index = i;
    assert( index > 0 );
    if( ringSize <= ( 0x01 << index ) )
        ringSize = 0x01 << index ;
    else
        ringSize = 0x01 << ( index + 1 );

    VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize ));
    return ringSize;
}


/*
 * During testing of core audio, I found that serious crashes could occur
 * if properties such as sample rate were changed multiple times in rapid
 * succession. The function below could be used to with a condition variable.
 * to prevent propertychanges from happening until the last property
 * change is acknowledged. Instead, I implemented a busy-wait, which is simpler
 * to implement b/c in second round of testing (nov '09) property changes occurred
 * quickly and so there was no real way to test the condition variable implementation.
 * therefore, this function is not used, but it is aluded to in commented code below,
 * since it represents a theoretically better implementation.
 */

OSStatus propertyProc(
        AudioObjectID inObjectID,
        UInt32 inNumberAddresses,
        const AudioObjectPropertyAddress* inAddresses,
        void* inClientData )
{
    // this is where we would set the condition variable
    return noErr;
}

/* sets the value of the given property and waits for the change to
   be acknowledged, and returns the final value, which is not guaranteed
   by this function to be the same as the desired value. Obviously, this
   function can only be used for data whose input and output are the
   same size and format, and their size and format are known in advance.
   whether or not the call succeeds, if the data is successfully read,
   it is returned in outPropertyData. If it is not read successfully,
   outPropertyData is zeroed, which may or may not be useful in
   determining if the property was read. */
PaError AudioDeviceSetPropertyNowAndWaitForChange(
        AudioDeviceID inDevice,
        UInt32 inChannel,
        Boolean isInput,
        AudioDevicePropertyID inPropertyID,
        UInt32 inPropertyDataSize,
        const void *inPropertyData,
        void *outPropertyData )
{
    OSStatus macErr;
    UInt32 outPropertyDataSize = inPropertyDataSize;

    /* First, see if it already has that value. If so, return. */
    macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel,
                                               isInput, inPropertyID,
                                               &outPropertyDataSize, outPropertyData );
    if( macErr ) {
        memset( outPropertyData, 0, inPropertyDataSize );
        goto failMac;
    }
    if( inPropertyDataSize!=outPropertyDataSize )
        return paInternalError;
    if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )
        return paNoError;

    /* Ideally, we'd use a condition variable to determine changes.
       we could set that up here. */

    /* If we were using a cond variable, we'd do something useful here,
       but for now, this is just to make 10.6 happy. */
    macErr = PaMacCore_AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,
                                                       inPropertyID, propertyProc,
             NULL );
    if( macErr )
        /* we couldn't add a listener. */
        goto failMac;

    /* set property */
    macErr = PaMacCore_AudioDeviceSetProperty( inDevice, NULL, inChannel,
                                               isInput, inPropertyID,
                                               inPropertyDataSize, inPropertyData );
    if( macErr )
        goto failMac;

    /* busy-wait up to 30 seconds for the property to change */
    /* busy-wait is justified here only because the correct alternative (condition variable)
       was hard to test, since most of the waiting ended up being for setting rather than
       getting in OS X 10.5. This was not the case in earlier OS versions. */
    struct timeval tv1, tv2;
    gettimeofday( &tv1, NULL );
    memcpy( &tv2, &tv1, sizeof( struct timeval ) );
    while( tv2.tv_sec - tv1.tv_sec < 30 ) {
        /* now read the property back out */
        macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel,
                 isInput, inPropertyID,
                 &outPropertyDataSize, outPropertyData );
        if( macErr ) {
            memset( outPropertyData, 0, inPropertyDataSize );
            goto failMac;
        }
        /* and compare... */
        if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) {
            PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL);
            return paNoError;
        }
        /* No match yet, so let's sleep and try again. */
        Pa_Sleep( 100 );
        gettimeofday( &tv2, NULL );
    }
    DBUG( ("Timeout waiting for device setting.\n" ) );

    PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL );
    return paNoError;

failMac:
    PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL );
    return ERR( macErr );
}

/*
 * Sets the sample rate the HAL device.
 * if requireExact: set the sample rate or fail.
 *
 * otherwise      : set the exact sample rate.
 *             If that fails, check for available sample rates, and choose one
 *             higher than the requested rate. If there isn't a higher one,
 *             just use the highest available.
 */
PaError setBestSampleRateForDevice( const AudioDeviceID device,
                                    const bool isOutput,
                                    const bool requireExact,
                                    const Float64 desiredSrate )
{
    const bool isInput = isOutput ? 0 : 1;
    Float64 srate;
    UInt32 propsize = sizeof( Float64 );
    OSErr err;
    AudioValueRange *ranges;
    int i=0;
    Float64 max  = -1; /*the maximum rate available*/
    Float64 best = -1; /*the lowest sample rate still greater than desired rate*/
    VDBUG(("Setting sample rate for device %ld to %g.\n",(long)device,(float)desiredSrate));

    /* -- try setting the sample rate -- */
    srate = 0;
    err = AudioDeviceSetPropertyNowAndWaitForChange(
            device, 0, isInput,
            kAudioDevicePropertyNominalSampleRate,
            propsize, &desiredSrate, &srate );

    /* -- if the rate agrees, and was changed, we are done -- */
    if( srate != 0 && srate == desiredSrate )
        return paNoError;
    /* -- if the rate agrees, and we got no errors, we are done -- */
    if( !err && srate == desiredSrate )
        return paNoError;
    /* -- we've failed if the rates disagree and we are setting input -- */
    if( requireExact )
        return paInvalidSampleRate;

    /* -- generate a list of available sample rates -- */
    err = PaMacCore_AudioDeviceGetPropertySize( device, 0, isInput,
            kAudioDevicePropertyAvailableNominalSampleRates,
            &propsize );
    if( err )
        return ERR( err );
    ranges = (AudioValueRange *)calloc( 1, propsize );
    if( !ranges )
        return paInsufficientMemory;
    err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
                                            kAudioDevicePropertyAvailableNominalSampleRates,
                                            &propsize, ranges );
    if( err )
    {
        free( ranges );
        return ERR( err );
    }
    VDBUG(("Requested sample rate of %g was not available.\n", (float)desiredSrate));
    VDBUG(("%lu Available Sample Rates are:\n",propsize/sizeof(AudioValueRange)));
#ifdef MAC_CORE_VERBOSE_DEBUG
    for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
        VDBUG( ("\t%g-%g\n",
                (float) ranges[i].mMinimum,
                (float) ranges[i].mMaximum ) );
#endif
    VDBUG(("-----\n"));

    /* -- now pick the best available sample rate -- */
    for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
    {
        if( ranges[i].mMaximum > max ) max = ranges[i].mMaximum;
        if( ranges[i].mMinimum > desiredSrate ) {
            if( best < 0 )
                best = ranges[i].mMinimum;
            else if( ranges[i].mMinimum < best )
                best = ranges[i].mMinimum;
        }
    }
    if( best < 0 )
        best = max;
    VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) );
    free( ranges );

    /* -- set the sample rate -- */
    propsize = sizeof( best );
    srate = 0;
    err = AudioDeviceSetPropertyNowAndWaitForChange(
            device, 0, isInput,
            kAudioDevicePropertyNominalSampleRate,
            propsize, &best, &srate );

    /* -- if the set rate matches, we are done -- */
    if( srate != 0 && srate == best )
        return paNoError;

    if( err )
        return ERR( err );

    /* -- otherwise, something weird happened: we didn't set the rate, and we got no errors. Just bail. */
    return paInternalError;
}


/*
   Attempts to set the requestedFramesPerBuffer. If it can't set the exact
   value, it settles for something smaller if available. If nothing smaller
   is available, it uses the smallest available size.
   actualFramesPerBuffer will be set to the actual value on successful return.
   OK to pass NULL to actualFramesPerBuffer.
   The logic is very similar too setBestSampleRate only failure here is
   not usually catastrophic.
*/
PaError setBestFramesPerBuffer( const AudioDeviceID device,
                                const bool isOutput,
                                UInt32 requestedFramesPerBuffer,
                                UInt32 *actualFramesPerBuffer )
{
    UInt32 afpb;
    const bool isInput = !isOutput;
    UInt32 propsize = sizeof(UInt32);
    OSErr err;
    AudioValueRange range;

    if( actualFramesPerBuffer == NULL )
    {
        actualFramesPerBuffer = &afpb;
    }

    /* -- try and set exact FPB -- */
    err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput,
                                            kAudioDevicePropertyBufferFrameSize,
                                            propsize, &requestedFramesPerBuffer);
    err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
                                            kAudioDevicePropertyBufferFrameSize,
                                            &propsize, actualFramesPerBuffer);
    if( err )
    {
        return ERR( err );
    }
    // Did we get the size we asked for?
    if( *actualFramesPerBuffer == requestedFramesPerBuffer )
    {
        return paNoError; /* we are done */
    }

    // Clip requested value against legal range for the device.
    propsize = sizeof(AudioValueRange);
    err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
                                            kAudioDevicePropertyBufferFrameSizeRange,
                                            &propsize, &range );
    if( err )
    {
        return ERR( err );
    }
    if( requestedFramesPerBuffer < range.mMinimum )
    {
        requestedFramesPerBuffer = range.mMinimum;
    }
    else if( requestedFramesPerBuffer > range.mMaximum )
    {
        requestedFramesPerBuffer = range.mMaximum;
    }

    /* --- set the buffer size (ignore errors) -- */
    propsize = sizeof( UInt32 );
    err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput,
                                            kAudioDevicePropertyBufferFrameSize,
                                            propsize, &requestedFramesPerBuffer );
    /* --- read the property to check that it was set -- */
    err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
                                            kAudioDevicePropertyBufferFrameSize,
                                            &propsize, actualFramesPerBuffer );

    if( err )
        return ERR( err );

    return paNoError;
}

/**********************
 *
 * XRun stuff
 *
 **********************/

struct PaMacXRunListNode_s {
    PaMacCoreStream *stream;
    struct PaMacXRunListNode_s *next;
} ;

typedef struct PaMacXRunListNode_s PaMacXRunListNode;

/** Always empty, so that it can always be the one returned by
    addToXRunListenerList. note that it's not a pointer. */
static PaMacXRunListNode firstXRunListNode;
static int xRunListSize;
static pthread_mutex_t xrunMutex;

OSStatus xrunCallback(
    AudioObjectID inDevice,
    UInt32 inNumberAddresses,
    const AudioObjectPropertyAddress* inAddresses,
    void * inClientData)
{
    PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData;
    bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput;

    int ret = pthread_mutex_trylock( &xrunMutex ) ;

    if( ret == 0 ) {

        node = node->next ; //skip the first node

        for( ; node; node=node->next ) {
            PaMacCoreStream *stream = node->stream;

            if( stream->state != ACTIVE )
                continue; //if the stream isn't active, we don't care if the device is dropping

            if( isInput ) {
                if( stream->inputDevice == inDevice )
                    OSAtomicOr32( paInputOverflow, &stream->xrunFlags );
            } else {
                if( stream->outputDevice == inDevice )
                    OSAtomicOr32( paOutputUnderflow, &stream->xrunFlags );
            }
        }

        pthread_mutex_unlock( &xrunMutex );
    }

    return 0;
}

int initializeXRunListenerList( void )
{
    xRunListSize = 0;
    bzero( (void *) &firstXRunListNode, sizeof(firstXRunListNode) );
    return pthread_mutex_init( &xrunMutex, NULL );
}
int destroyXRunListenerList( void )
{
    PaMacXRunListNode *node;
    node = firstXRunListNode.next;
    while( node ) {
        PaMacXRunListNode *tmp = node;
        node = node->next;
        free( tmp );
    }
    xRunListSize = 0;
    return pthread_mutex_destroy( &xrunMutex );
}

void *addToXRunListenerList( void *stream )
{
    pthread_mutex_lock( &xrunMutex );
    PaMacXRunListNode *newNode;
    // setup new node:
    newNode = (PaMacXRunListNode *) malloc( sizeof( PaMacXRunListNode ) );
    newNode->stream = (PaMacCoreStream *) stream;
    newNode->next = firstXRunListNode.next;
    // insert:
    firstXRunListNode.next = newNode;
    pthread_mutex_unlock( &xrunMutex );

    return &firstXRunListNode;
}

int removeFromXRunListenerList( void *stream )
{
    pthread_mutex_lock( &xrunMutex );
    PaMacXRunListNode *node, *prev;
    prev = &firstXRunListNode;
    node = firstXRunListNode.next;
    while( node ) {
        if( node->stream == stream ) {
            //found it:
            --xRunListSize;
            prev->next = node->next;
            free( node );
            pthread_mutex_unlock( &xrunMutex );
            return xRunListSize;
        }
        prev = prev->next;
        node = node->next;
    }

    pthread_mutex_unlock( &xrunMutex );
    // failure
    return xRunListSize;
}