pa_mac_core.c 111 KB
Newer Older
bjornroche's avatar
bjornroche committed
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
/*
 * Implementation of the PortAudio API for Apple AUHAL
 *
 * 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 pa_mac_core
 @ingroup hostapi_src
 @author Bjorn Roche
 @brief AUHAL implementation of PortAudio
*/

/* FIXME: not all error conditions call PaUtil_SetLastHostErrorInfo()
 * PaMacCore_SetError() will do this.
 */

#include "pa_mac_core_internal.h"

#include <string.h> /* strlen(), memcmp() etc. */
#include <libkern/OSAtomic.h>

#include "pa_mac_core.h"
#include "pa_mac_core_utilities.h"
#include "pa_mac_core_blocking.h"


#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
79 80 81 82
	
/* This is a reasonable size for a small buffer based on experience. */
#define PA_MAC_SMALL_BUFFER_SIZE    (64)
	
bjornroche's avatar
bjornroche committed
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
/* prototypes for functions declared in this file */
PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

/*
 * Function declared in pa_mac_core.h. Sets up a PaMacCoreStreamInfoStruct
 * with the requested flags and initializes channel map.
 */
void PaMacCore_SetupStreamInfo(  PaMacCoreStreamInfo *data, const unsigned long flags )
{
   bzero( data, sizeof( PaMacCoreStreamInfo ) );
   data->size = sizeof( PaMacCoreStreamInfo );
   data->hostApiType = paCoreAudio;
   data->version = 0x01;
   data->flags = flags;
   data->channelMap = NULL;
   data->channelMapSize = 0;
}

/*
 * Function declared in pa_mac_core.h. Adds channel mapping to a PaMacCoreStreamInfoStruct
 */
void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, const unsigned long channelMapSize )
{
   data->channelMap = channelMap;
   data->channelMapSize = channelMapSize;
}
static char *channelName = NULL;
static int channelNameSize = 0;
static bool ensureChannelNameSize( int size )
{
   if( size >= channelNameSize ) {
      free( channelName );
      channelName = (char *) malloc( ( channelNameSize = size ) + 1 );
      if( !channelName ) {
         channelNameSize = 0;
         return false;
      }
   }
   return true;
}
/*
 * Function declared in pa_mac_core.h. retrives channel names.
 */
const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input )
{
   struct PaUtilHostApiRepresentation *hostApi;
   PaError err;
   OSStatus error;
   err = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );
   assert(err == paNoError);
   if( err != paNoError )
      return NULL;
   PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;
   AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device];

   UInt32 size = 0;

   error = AudioDeviceGetPropertyInfo( hostApiDevice,
                                       channelIndex + 1,
                                       input,
                                       kAudioDevicePropertyChannelName,
                                       &size,
                                       NULL );
   if( error ) {
      //try the CFString
      CFStringRef name;
      bool isDeviceName = false;
      size = sizeof( name );
      error = AudioDeviceGetProperty( hostApiDevice,
                                      channelIndex + 1,
                                      input,
                                      kAudioDevicePropertyChannelNameCFString,
                                      &size,
                                      &name );
      if( error ) { //as a last-ditch effort, get the device name. Later we'll append the channel number.
         size = sizeof( name );
         error = AudioDeviceGetProperty( hostApiDevice,
                                      channelIndex + 1,
                                      input,
                                      kAudioDevicePropertyDeviceNameCFString,
                                      &size,
                                      &name );
         if( error )
            return NULL;
         isDeviceName = true;
      }
      if( isDeviceName ) {
         name = CFStringCreateWithFormat( NULL, NULL, CFSTR( "%@: %d"), name, channelIndex + 1 );
      }

      CFIndex length = CFStringGetLength(name);
      while( ensureChannelNameSize( length * sizeof(UniChar) + 1 ) ) {
         if( CFStringGetCString( name, channelName, channelNameSize, kCFStringEncodingUTF8 ) ) {
            if( isDeviceName )
               CFRelease( name );
            return channelName;
         }
         if( length == 0 )
            ++length;
         length *= 2;
      }
      if( isDeviceName )
         CFRelease( name );
      return NULL;
   }

   //continue with C string:
   if( !ensureChannelNameSize( size ) )
      return NULL;

   error = AudioDeviceGetProperty( hostApiDevice,
                                   channelIndex + 1,
                                   input,
                                   kAudioDevicePropertyChannelName,
                                   &size,
                                   channelName );

   if( error ) {
      ERR( error );
      return NULL;
   }
   return channelName;
}





AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s )
{
    PaMacCoreStream *stream = (PaMacCoreStream*)s;
    VVDBUG(("PaMacCore_GetStreamInputHandle()\n"));

    return ( stream->inputDevice );
}

AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s )
{
    PaMacCoreStream *stream = (PaMacCoreStream*)s;
    VVDBUG(("PaMacCore_GetStreamOutputHandle()\n"));

    return ( stream->outputDevice );
}

#ifdef __cplusplus
}
#endif /* __cplusplus */

#define RING_BUFFER_ADVANCE_DENOMINATOR (4)

static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                                  const PaStreamParameters *inputParameters,
                                  const PaStreamParameters *outputParameters,
                                  double sampleRate );
static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                           PaStream** s,
                           const PaStreamParameters *inputParameters,
                           const PaStreamParameters *outputParameters,
                           double sampleRate,
                           unsigned long framesPerBuffer,
                           PaStreamFlags streamFlags,
                           PaStreamCallback *streamCallback,
                           void *userData );
static PaError CloseStream( PaStream* stream );
static PaError StartStream( PaStream *stream );
static PaError StopStream( PaStream *stream );
static PaError AbortStream( PaStream *stream );
static PaError IsStreamStopped( PaStream *s );
static PaError IsStreamActive( PaStream *stream );
static PaTime GetStreamTime( PaStream *stream );
static OSStatus AudioIOProc( void *inRefCon,
                               AudioUnitRenderActionFlags *ioActionFlags,
                               const AudioTimeStamp *inTimeStamp,
                               UInt32 inBusNumber,
                               UInt32 inNumberFrames,
                               AudioBufferList *ioData );
static double GetStreamCpuLoad( PaStream* stream );

static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
                               PaDeviceInfo *deviceInfo,
                               AudioDeviceID macCoreDeviceId,
                               int isInput);

static PaError OpenAndSetupOneAudioUnit(
                                   const PaMacCoreStream *stream,
                                   const PaStreamParameters *inStreamParams,
                                   const PaStreamParameters *outStreamParams,
                                   const UInt32 requestedFramesPerBuffer,
                                   UInt32 *actualInputFramesPerBuffer,
                                   UInt32 *actualOutputFramesPerBuffer,
                                   const PaMacAUHAL *auhalHostApi,
                                   AudioUnit *audioUnit,
                                   AudioConverterRef *srConverter,
                                   AudioDeviceID *audioDevice,
                                   const double sampleRate,
                                   void *refCon );

/* for setting errors. */
#define PA_AUHAL_SET_LAST_HOST_ERROR( errorCode, errorText ) \
    PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText )

/*
 * Callback called when starting or stopping a stream.
 */
static void startStopCallback(
   void *               inRefCon,
   AudioUnit            ci,
   AudioUnitPropertyID  inID,
   AudioUnitScope       inScope,
   AudioUnitElement     inElement )
{
   PaMacCoreStream *stream = (PaMacCoreStream *) inRefCon;
   UInt32 isRunning;
   UInt32 size = sizeof( isRunning );
   OSStatus err;
   err = AudioUnitGetProperty( ci, kAudioOutputUnitProperty_IsRunning, inScope, inElement, &isRunning, &size );
   assert( !err );
   if( err )
      isRunning = false; //it's very unclear what to do in case of error here. There's no real way to notify the user, and crashing seems unreasonable.
   if( isRunning )
      return; //We are only interested in when we are stopping
   // -- if we are using 2 I/O units, we only need one notification!
   if( stream->inputUnit && stream->outputUnit && stream->inputUnit != stream->outputUnit && ci == stream->inputUnit )
      return;
   PaStreamFinishedCallback *sfc = stream->streamRepresentation.streamFinishedCallback;
   if( stream->state == STOPPING )
      stream->state = STOPPED ;
   if( sfc )
      sfc( stream->streamRepresentation.userData );
}


/*currently, this is only used in initialization, but it might be modified
  to be used when the list of devices changes.*/
static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi)
{
    UInt32 size;
    UInt32 propsize;
    VVDBUG(("gatherDeviceInfo()\n"));
    /* -- free any previous allocations -- */
    if( auhalHostApi->devIds )
        PaUtil_GroupFreeMemory(auhalHostApi->allocations, auhalHostApi->devIds);
    auhalHostApi->devIds = NULL;

    /* -- figure out how many devices there are -- */
    AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices,
                                  &propsize,
                                  NULL );
    auhalHostApi->devCount = propsize / sizeof( AudioDeviceID );

    VDBUG( ( "Found %ld device(s).\n", auhalHostApi->devCount ) );

    /* -- copy the device IDs -- */
    auhalHostApi->devIds = (AudioDeviceID *)PaUtil_GroupAllocateMemory(
                             auhalHostApi->allocations,
                             propsize );
    if( !auhalHostApi->devIds )
        return paInsufficientMemory;
    AudioHardwareGetProperty( kAudioHardwarePropertyDevices,
                                  &propsize,
                                  auhalHostApi->devIds );
#ifdef MAC_CORE_VERBOSE_DEBUG
    {
       int i;
       for( i=0; i<auhalHostApi->devCount; ++i )
          printf( "Device %d\t: %ld\n", i, auhalHostApi->devIds[i] );
    }
#endif

    size = sizeof(AudioDeviceID);
    auhalHostApi->defaultIn  = kAudioDeviceUnknown;
    auhalHostApi->defaultOut = kAudioDeviceUnknown;

    /* determine the default device. */
    /* I am not sure how these calls to AudioHardwareGetProperty()
       could fail, but in case they do, we use the first available
       device as the default. */
    if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
                     &size,
                     &auhalHostApi->defaultIn) ) {
       int i;
       auhalHostApi->defaultIn  = kAudioDeviceUnknown;
       VDBUG(("Failed to get default input device from OS."));
       VDBUG((" I will substitute the first available input Device."));
       for( i=0; i<auhalHostApi->devCount; ++i ) {
          PaDeviceInfo devInfo;
          if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
                                   auhalHostApi->devIds[i], TRUE ) )
             if( devInfo.maxInputChannels ) {
                auhalHostApi->defaultIn = auhalHostApi->devIds[i];
                break;
             }
       }
    }   
    if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
                     &size,
                     &auhalHostApi->defaultOut) ) {
       int i;
       auhalHostApi->defaultIn  = kAudioDeviceUnknown;
       VDBUG(("Failed to get default output device from OS."));
       VDBUG((" I will substitute the first available output Device."));
       for( i=0; i<auhalHostApi->devCount; ++i ) {
          PaDeviceInfo devInfo;
          if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
                                   auhalHostApi->devIds[i], FALSE ) )
             if( devInfo.maxOutputChannels ) {
                auhalHostApi->defaultOut = auhalHostApi->devIds[i];
                break;
             }
       }
    }   

    VDBUG( ( "Default in : %ld\n", auhalHostApi->defaultIn  ) );
    VDBUG( ( "Default out: %ld\n", auhalHostApi->defaultOut ) );

    return paNoError;
}

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
/* =================================================================================================== */
/**
 * @internal
 * @brief Clip the desired size against the allowed IO buffer size range for the device.
 */
static PaError ClipToDeviceBufferSize( AudioDeviceID macCoreDeviceId,
									int isInput, UInt32 desiredSize, UInt32 *allowedSize )
{
	UInt32 resultSize = desiredSize;
	AudioValueRange audioRange;
	UInt32 propSize = sizeof( audioRange );
	PaError err = WARNING(AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
	resultSize = MAX( resultSize, audioRange.mMinimum );
	resultSize = MIN( resultSize, audioRange.mMaximum );
	*allowedSize = resultSize;
	return err;
}

/* =================================================================================================== */
#if 0
422
static void DumpDeviceProperties( AudioDeviceID macCoreDeviceId,
423 424
                          int isInput )
{
425 426
    PaError err;
    int i;
427 428 429 430 431
    UInt32 propSize;
    UInt32 deviceLatency;
    UInt32 streamLatency;
    UInt32 bufferFrames;
    UInt32 safetyOffset;
432
    AudioStreamID streamIDs[128];
433
    
434
    printf("\n======= latency query : macCoreDeviceId = %d, isInput %d =======\n", (int)macCoreDeviceId, isInput );    
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    
    propSize = sizeof(UInt32);
    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames));
    printf("kAudioDevicePropertyBufferFrameSize: err = %d, propSize = %d, value = %d\n", err, propSize, bufferFrames );
    
    propSize = sizeof(UInt32);
    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset));
    printf("kAudioDevicePropertySafetyOffset: err = %d, propSize = %d, value = %d\n", err, propSize, safetyOffset );
    
    propSize = sizeof(UInt32);
    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency));
    printf("kAudioDevicePropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, deviceLatency );
    
    AudioValueRange audioRange;
    propSize = sizeof( audioRange );
    err = WARNING(AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, minimum = %g\n", err, propSize, audioRange.mMinimum);
    printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, maximum = %g\n", err, propSize, audioRange.mMaximum );
    
    /* Get the streams from the device and query their latency. */
    propSize = sizeof(streamIDs);
    err  = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0]));
    int numStreams = propSize / sizeof(AudioStreamID);
    for( i=0; i<numStreams; i++ )
    {
        printf("Stream #%d = %d---------------------- \n", i, streamIDs[i] );
        
        propSize = sizeof(UInt32);
        err  = WARNING(AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency));
        printf("  kAudioStreamPropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, streamLatency );
    }
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
}
#endif

/* =================================================================================================== */
/**
 * @internal
 * Calculate the fixed latency from the system and the device.
 * Sum of kAudioStreamPropertyLatency +
 *        kAudioDevicePropertySafetyOffset +
 *        kAudioDevicePropertyLatency
 *
 * Some useful info from Jeff Moore on latency.
 * http://osdir.com/ml/coreaudio-api/2010-01/msg00046.html
 * http://osdir.com/ml/coreaudio-api/2009-07/msg00140.html
 */
static PaError CalculateFixedDeviceLatency( AudioDeviceID macCoreDeviceId, int isInput, UInt32 *fixedLatencyPtr )
{
483
    PaError err;
484 485 486 487
    UInt32 propSize;
    UInt32 deviceLatency;
    UInt32 streamLatency;
    UInt32 safetyOffset;
488
    AudioStreamID streamIDs[1];
489
    
490 491 492 493
    // To get stream latency we have to get a streamID from the device.
    // We are only going to look at the first stream so only fetch one stream.
    propSize = sizeof(streamIDs);
    err  = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0]));
494
    if( err != paNoError ) goto error;
495 496 497 498 499
    if( propSize == sizeof(AudioStreamID) )
    {        
        propSize = sizeof(UInt32);
        err  = WARNING(AudioStreamGetProperty(streamIDs[0], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency));
    }
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
    
    propSize = sizeof(UInt32);
    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset));
    if( err != paNoError ) goto error;
    
    propSize = sizeof(UInt32);
    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency));
    if( err != paNoError ) goto error;

    *fixedLatencyPtr = deviceLatency + streamLatency + safetyOffset;
    return err;
error:
    return err;
}

/* =================================================================================================== */
static PaError CalculateDefaultDeviceLatencies( AudioDeviceID macCoreDeviceId,
                                               int isInput, UInt32 *lowLatencyFramesPtr,
                                               UInt32 *highLatencyFramesPtr )
{
    UInt32 propSize;
    UInt32 bufferFrames = 0;
    UInt32 fixedLatency = 0;
    UInt32 clippedMinBufferSize = 0;
    
525 526
    //DumpDeviceProperties( macCoreDeviceId, isInput );
    
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
    PaError err = CalculateFixedDeviceLatency( macCoreDeviceId, isInput, &fixedLatency );
    if( err != paNoError ) goto error;
    
    // For low latency use a small fixed size buffer clipped to the device range.
    err = ClipToDeviceBufferSize( macCoreDeviceId, isInput, PA_MAC_SMALL_BUFFER_SIZE, &clippedMinBufferSize );
    if( err != paNoError ) goto error;
    
    // For high latency use the default device buffer size.
    propSize = sizeof(UInt32);
    err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames));
    if( err != paNoError ) goto error;
    
    *lowLatencyFramesPtr = fixedLatency + clippedMinBufferSize;
    *highLatencyFramesPtr = fixedLatency + bufferFrames;
    
    return err;
error:
    return err;
}

/* =================================================================================================== */

bjornroche's avatar
bjornroche committed
549 550 551 552 553 554 555 556 557 558
static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
                               PaDeviceInfo *deviceInfo,
                               AudioDeviceID macCoreDeviceId,
                               int isInput)
{
    UInt32 propSize;
    PaError err = paNoError;
    UInt32 i;
    int numChannels = 0;
    AudioBufferList *buflist = NULL;
559
    
bjornroche's avatar
bjornroche committed
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    VVDBUG(("GetChannelInfo()\n"));

    /* Get the number of channels from the stream configuration.
       Fail if we can't get this. */

    err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL));
    if (err)
        return err;

    buflist = PaUtil_AllocateMemory(propSize);
    if( !buflist )
       return paInsufficientMemory;
    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist));
    if (err)
        goto error;

    for (i = 0; i < buflist->mNumberBuffers; ++i)
        numChannels += buflist->mBuffers[i].mNumberChannels;

    if (isInput)
        deviceInfo->maxInputChannels = numChannels;
    else
        deviceInfo->maxOutputChannels = numChannels;
      
584
    if (numChannels > 0) /* do not try to retrieve the latency if there are no channels. */
bjornroche's avatar
bjornroche committed
585
    {
586 587 588 589 590 591
        /* Get the latency.  Don't fail if we can't get this. */
        /* default to something reasonable */
        deviceInfo->defaultLowInputLatency = .01;
        deviceInfo->defaultHighInputLatency = .10;
        deviceInfo->defaultLowOutputLatency = .01;
        deviceInfo->defaultHighOutputLatency = .10;        
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
        UInt32 lowLatencyFrames = 0;
        UInt32 highLatencyFrames = 0;
        err = CalculateDefaultDeviceLatencies( macCoreDeviceId, isInput, &lowLatencyFrames, &highLatencyFrames );
        if( err == 0 )
        {
            
            double lowLatencySeconds = lowLatencyFrames / deviceInfo->defaultSampleRate;
            double highLatencySeconds = highLatencyFrames / deviceInfo->defaultSampleRate;
            if (isInput)
            {
                deviceInfo->defaultLowInputLatency = lowLatencySeconds;
                deviceInfo->defaultHighInputLatency = highLatencySeconds;
            }
            else
            {
                deviceInfo->defaultLowOutputLatency = lowLatencySeconds;
                deviceInfo->defaultHighOutputLatency = highLatencySeconds;
            }
        }
bjornroche's avatar
bjornroche committed
611 612 613 614 615 616 617 618
    }
    PaUtil_FreeMemory( buflist );
    return paNoError;
 error:
    PaUtil_FreeMemory( buflist );
    return err;
}

619
/* =================================================================================================== */
bjornroche's avatar
bjornroche committed
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
static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi,
                                     PaDeviceInfo *deviceInfo,
                                     AudioDeviceID macCoreDeviceId,
                                     PaHostApiIndex hostApiIndex )
{
    Float64 sampleRate;
    char *name;
    PaError err = paNoError;
    UInt32 propSize;

    VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId));

    memset(deviceInfo, 0, sizeof(deviceInfo));

    deviceInfo->structVersion = 2;
    deviceInfo->hostApi = hostApiIndex;

    /* Get the device name.  Fail if we can't get it. */
    err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL));
    if (err)
        return err;

    name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize);
    if ( !name )
        return paInsufficientMemory;
    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name));
    if (err)
        return err;
    deviceInfo->name = name;

    /* Try to get the default sample rate.  Don't fail if we can't get this. */
    propSize = sizeof(Float64);
    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate));
    if (err)
        deviceInfo->defaultSampleRate = 0.0;
    else
        deviceInfo->defaultSampleRate = sampleRate;

    /* Get the maximum number of input and output channels.  Fail if we can't get this. */

    err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 1);
    if (err)
        return err;

    err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 0);
    if (err)
        return err;

    return paNoError;
}

PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
{
    PaError result = paNoError;
    int i;
675
    PaMacAUHAL *auhalHostApi = NULL;
bjornroche's avatar
bjornroche committed
676 677 678 679
    PaDeviceInfo *deviceInfoArray;
    int unixErr;

    VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex));
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
	
	SInt32 major;
	SInt32 minor;
	Gestalt(gestaltSystemVersionMajor, &major);
	Gestalt(gestaltSystemVersionMinor, &minor);
	
	// Starting with 10.6 systems, the HAL notification thread is created internally
	if (major == 10 && minor >= 6) {
		CFRunLoopRef theRunLoop = NULL;
		AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
		OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
		if (osErr != noErr) {
			goto error;
		}
	}
	
bjornroche's avatar
bjornroche committed
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 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
    unixErr = initializeXRunListenerList();
    if( 0 != unixErr ) {
       return UNIX_ERR(unixErr);
    }

    auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) );
    if( !auhalHostApi )
    {
        result = paInsufficientMemory;
        goto error;
    }

    auhalHostApi->allocations = PaUtil_CreateAllocationGroup();
    if( !auhalHostApi->allocations )
    {
        result = paInsufficientMemory;
        goto error;
    }

    auhalHostApi->devIds = NULL;
    auhalHostApi->devCount = 0;

    /* get the info we need about the devices */
    result = gatherDeviceInfo( auhalHostApi );
    if( result != paNoError )
       goto error;

    *hostApi = &auhalHostApi->inheritedHostApiRep;
    (*hostApi)->info.structVersion = 1;
    (*hostApi)->info.type = paCoreAudio;
    (*hostApi)->info.name = "Core Audio";

    (*hostApi)->info.defaultInputDevice = paNoDevice;
    (*hostApi)->info.defaultOutputDevice = paNoDevice;

    (*hostApi)->info.deviceCount = 0;  

    if( auhalHostApi->devCount > 0 )
    {
        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
                auhalHostApi->allocations, sizeof(PaDeviceInfo*) * auhalHostApi->devCount);
        if( !(*hostApi)->deviceInfos )
        {
            result = paInsufficientMemory;
            goto error;
        }

        /* allocate all device info structs in a contiguous block */
        deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(
                auhalHostApi->allocations, sizeof(PaDeviceInfo) * auhalHostApi->devCount );
        if( !deviceInfoArray )
        {
            result = paInsufficientMemory;
            goto error;
        }

        for( i=0; i < auhalHostApi->devCount; ++i )
        {
            int err;
            err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i],
                                      auhalHostApi->devIds[i],
                                      hostApiIndex );
            if (err == paNoError)
            { /* copy some info and set the defaults */
                (*hostApi)->deviceInfos[(*hostApi)->info.deviceCount] = &deviceInfoArray[i];
                if (auhalHostApi->devIds[i] == auhalHostApi->defaultIn)
                    (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
                if (auhalHostApi->devIds[i] == auhalHostApi->defaultOut)
                    (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
                (*hostApi)->info.deviceCount++;
            }
            else
            { /* there was an error. we need to shift the devices down, so we ignore this one */
                int j;
                auhalHostApi->devCount--;
                for( j=i; j<auhalHostApi->devCount; ++j )
                   auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1];
                i--;
            }
        }
    }

    (*hostApi)->Terminate = Terminate;
    (*hostApi)->OpenStream = OpenStream;
    (*hostApi)->IsFormatSupported = IsFormatSupported;

    PaUtil_InitializeStreamInterface( &auhalHostApi->callbackStreamInterface,
                                      CloseStream, StartStream,
                                      StopStream, AbortStream, IsStreamStopped,
                                      IsStreamActive,
                                      GetStreamTime, GetStreamCpuLoad,
                                      PaUtil_DummyRead, PaUtil_DummyWrite,
                                      PaUtil_DummyGetReadAvailable,
                                      PaUtil_DummyGetWriteAvailable );

    PaUtil_InitializeStreamInterface( &auhalHostApi->blockingStreamInterface,
                                      CloseStream, StartStream,
                                      StopStream, AbortStream, IsStreamStopped,
                                      IsStreamActive,
                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
                                      ReadStream, WriteStream,
                                      GetStreamReadAvailable,
                                      GetStreamWriteAvailable );

    return result;

error:
    if( auhalHostApi )
    {
        if( auhalHostApi->allocations )
        {
            PaUtil_FreeAllAllocations( auhalHostApi->allocations );
            PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
        }
                
        PaUtil_FreeMemory( auhalHostApi );
    }
    return result;
}


static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
{
    int unixErr;

    PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;

    VVDBUG(("Terminate()\n"));

    unixErr = destroyXRunListenerList();
    if( 0 != unixErr )
       UNIX_ERR(unixErr);

    /*
        IMPLEMENT ME:
            - clean up any resources not handled by the allocation group
        TODO: Double check that everything is handled by alloc group
    */

    if( auhalHostApi->allocations )
    {
        PaUtil_FreeAllAllocations( auhalHostApi->allocations );
        PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
    }

    PaUtil_FreeMemory( auhalHostApi );
}


static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                                  const PaStreamParameters *inputParameters,
                                  const PaStreamParameters *outputParameters,
                                  double sampleRate )
{
    int inputChannelCount, outputChannelCount;
    PaSampleFormat inputSampleFormat, outputSampleFormat;

    VVDBUG(("IsFormatSupported(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld sampleRate=%g\n",
                inputParameters  ? inputParameters->channelCount  : -1,
                inputParameters  ? inputParameters->sampleFormat  : -1,
                outputParameters ? outputParameters->channelCount : -1,
                outputParameters ? outputParameters->sampleFormat : -1,
                (float) sampleRate ));
 
    /** These first checks are standard PA checks. We do some fancier checks
        later. */
    if( inputParameters )
    {
        inputChannelCount = inputParameters->channelCount;
        inputSampleFormat = inputParameters->sampleFormat;

        /* all standard sample formats are supported by the buffer adapter,
            this implementation doesn't support any custom sample formats */
        if( inputSampleFormat & paCustomFormat )
            return paSampleFormatNotSupported;
            
        /* unless alternate device specification is supported, reject the use of
            paUseHostApiSpecificDeviceSpecification */

        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
            return paInvalidDevice;

        /* check that input device can support inputChannelCount */
        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
            return paInvalidChannelCount;
    }
    else
    {
        inputChannelCount = 0;
    }

    if( outputParameters )
    {
        outputChannelCount = outputParameters->channelCount;
        outputSampleFormat = outputParameters->sampleFormat;

        /* all standard sample formats are supported by the buffer adapter,
            this implementation doesn't support any custom sample formats */
        if( outputSampleFormat & paCustomFormat )
            return paSampleFormatNotSupported;
            
        /* unless alternate device specification is supported, reject the use of
            paUseHostApiSpecificDeviceSpecification */

        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
            return paInvalidDevice;

        /* check that output device can support outputChannelCount */
        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
            return paInvalidChannelCount;

    }
    else
    {
        outputChannelCount = 0;
    }
 
    /* FEEDBACK */
    /*        I think the only way to check a given format SR combo is     */
    /*        to try opening it. This could be disruptive, is that Okay?   */
    /*        The alternative is to just read off available sample rates,  */
    /*        but this will not work %100 of the time (eg, a device that   */
    /*        supports N output at one rate but only N/2 at a higher rate.)*/

    /* The following code opens the device with the requested parameters to
       see if it works. */
    {
       PaError err;
       PaStream *s;
       err = OpenStream( hostApi, &s, inputParameters, outputParameters,
                           sampleRate, 1024, 0, (PaStreamCallback *)1, NULL );
       if( err != paNoError && err != paInvalidSampleRate )
          DBUG( ( "OpenStream @ %g returned: %d: %s\n",
                  (float) sampleRate, err, Pa_GetErrorText( err ) ) );
       if( err ) 
          return err;
       err = CloseStream( s );
       if( err ) {
          /* FEEDBACK: is this more serious? should we assert? */
          DBUG( ( "WARNING: could not close Stream. %d: %s\n",
                  err, Pa_GetErrorText( err ) ) );
       }
    }

    return paFormatIsSupported;
}

943 944 945 946 947 948 949 950 951 952 953 954 955
/* ================================================================================= */
static void InitializeDeviceProperties( PaMacCoreDeviceProperties *deviceProperties )
{
    memset( deviceProperties, 0, sizeof(PaMacCoreDeviceProperties) );
    deviceProperties->sampleRate = 1.0; // Better than random. Overwritten by actual values later on.
    deviceProperties->samplePeriod = 1.0 / deviceProperties->sampleRate;
}

static Float64 CalculateSoftwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties )
{
    UInt32 latencyFrames = deviceProperties->bufferFrameSize + deviceProperties->deviceLatency + deviceProperties->safetyOffset;
    return latencyFrames * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster
}
956

957
static Float64 CalculateHardwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties )
958
{
959
    return deviceProperties->deviceLatency * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster
960 961
}

962 963 964 965 966
/* Calculate values used to convert Apple timestamps into PA timestamps
 * from the device properties. The final results of this calculation
 * will be used in the audio callback function.
 */
static void UpdateTimeStampOffsets( PaMacCoreStream *stream )
967
{
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    Float64 inputSoftwareLatency = 0.0;
    Float64 inputHardwareLatency = 0.0;
    Float64 outputSoftwareLatency = 0.0;
    Float64 outputHardwareLatency = 0.0;
    
    if( stream->inputUnit != NULL )
    {
        inputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->inputProperties );
        inputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->inputProperties );
    }    
    if( stream->outputUnit != NULL )
    {
        outputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->outputProperties );
        outputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->outputProperties );
    }    
    
    /* We only need a mutex around setting these variables as a group. */
985
	pthread_mutex_lock( &stream->timingInformationMutex );
986 987 988
    stream->timestampOffsetCombined = inputSoftwareLatency + outputSoftwareLatency;
    stream->timestampOffsetInputDevice = inputHardwareLatency;
    stream->timestampOffsetOutputDevice = outputHardwareLatency;
989 990 991
	pthread_mutex_unlock( &stream->timingInformationMutex );
}

992 993 994
/* ================================================================================= */
/* Query sample rate property. */
static OSStatus UpdateSampleRateFromDeviceProperty( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput )
995
{
996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    PaMacCoreDeviceProperties * deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
	/* FIXME: not sure if this should be the sample rate of the output device or the output unit */
	Float64 actualSampleRate = deviceProperties->sampleRate;
	UInt32 propSize = sizeof(Float64);
    OSStatus osErr = AudioDeviceGetProperty( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, &propSize, &actualSampleRate);
	if( (osErr == noErr) && (actualSampleRate > 1000.0) ) // avoid divide by zero if there's an error
	{
        deviceProperties->sampleRate = actualSampleRate;
        deviceProperties->samplePeriod = 1.0 / actualSampleRate;
    }
    return osErr;
1007 1008
}

1009
static OSStatus AudioDevicePropertyActualSampleRateListenerProc( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, void *inClientData )
1010 1011
{
	PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
1012 1013 1014 1015
    
    // Make sure the callback is operating on a stream that is still valid!
    assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC );

1016 1017 1018 1019 1020 1021
	OSStatus osErr = UpdateSampleRateFromDeviceProperty( stream, inDevice, isInput );
    if( osErr == noErr )
    {
        UpdateTimeStampOffsets( stream );
    }
    return osErr;
1022 1023
}

1024 1025
/* ================================================================================= */
static OSStatus QueryUInt32DeviceProperty( AudioDeviceID deviceID, Boolean isInput, AudioDevicePropertyID propertyID, UInt32 *outValue )
1026
{
1027 1028 1029 1030 1031 1032 1033 1034
	UInt32 propertyValue = 0;
	UInt32 propertySize = sizeof(UInt32);
	OSStatus osErr = AudioDeviceGetProperty( deviceID, 0, isInput, propertyID, &propertySize, &propertyValue);
	if( osErr == noErr )
	{
        *outValue = propertyValue;
	}
    return osErr;
1035 1036
}

1037
static OSStatus AudioDevicePropertyGenericListenerProc( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, void *inClientData )
1038
{
1039
    OSStatus osErr = noErr;
1040
	PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
1041 1042 1043 1044
    
    // Make sure the callback is operating on a stream that is still valid!
    assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC );
    
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
    UInt32 *valuePtr = NULL;
    switch( inPropertyID )
    {
        case kAudioDevicePropertySafetyOffset:
            valuePtr = &deviceProperties->safetyOffset;
            break;
                        
        case kAudioDevicePropertyLatency:
            valuePtr = &deviceProperties->deviceLatency;
            break;
            
        case kAudioDevicePropertyBufferFrameSize:
            valuePtr = &deviceProperties->bufferFrameSize;
            break;            
    }
    if( valuePtr != NULL )
    {
        osErr = QueryUInt32DeviceProperty( inDevice, isInput, inPropertyID, valuePtr );
        if( osErr == noErr )
        {
            UpdateTimeStampOffsets( stream );
        }
    }
    return osErr;
}
1071

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
/* ================================================================================= */
/*
 * Setup listeners in case device properties change during the run. */
static OSStatus SetupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput )
{
    OSStatus osErr = noErr;
    PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
    
    // Start with the current values for the device properties.
    UpdateSampleRateFromDeviceProperty( stream, deviceID, isInput );
    
    if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
                                           kAudioDevicePropertyLatency, &deviceProperties->deviceLatency )) != noErr ) return osErr;
    if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
                                           kAudioDevicePropertyBufferFrameSize, &deviceProperties->bufferFrameSize )) != noErr ) return osErr;
    if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
                                           kAudioDevicePropertySafetyOffset, &deviceProperties->safetyOffset )) != noErr ) return osErr;
    
    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, 
                                   AudioDevicePropertyActualSampleRateListenerProc, stream );
    
    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioStreamPropertyLatency, 
                                   AudioDevicePropertyGenericListenerProc, stream );
    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, 
                                   AudioDevicePropertyGenericListenerProc, stream );
    AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, 
                                   AudioDevicePropertyGenericListenerProc, stream );
    
    return osErr;
1101 1102
}

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
static void CleanupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput )
{    
    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, 
                                   AudioDevicePropertyActualSampleRateListenerProc );
    
    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyLatency, 
                                   AudioDevicePropertyGenericListenerProc );	
    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, 
                                   AudioDevicePropertyGenericListenerProc );
    AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, 
                                   AudioDevicePropertyGenericListenerProc );
}
1115

1116
/* ================================================================================= */
bjornroche's avatar
bjornroche committed
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
static PaError OpenAndSetupOneAudioUnit(
                                   const PaMacCoreStream *stream,
                                   const PaStreamParameters *inStreamParams,
                                   const PaStreamParameters *outStreamParams,
                                   const UInt32 requestedFramesPerBuffer,
                                   UInt32 *actualInputFramesPerBuffer,
                                   UInt32 *actualOutputFramesPerBuffer,
                                   const PaMacAUHAL *auhalHostApi,
                                   AudioUnit *audioUnit,
                                   AudioConverterRef *srConverter,
                                   AudioDeviceID *audioDevice,
                                   const double sampleRate,
                                   void *refCon )
{
    ComponentDescription desc;
    Component comp;
    /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/
    AudioStreamBasicDescription desiredFormat;
    OSStatus result = noErr;
    PaError paResult = paNoError;
    int line = 0;
    UInt32 callbackKey;
    AURenderCallbackStruct rcbs;
    unsigned long macInputStreamFlags  = paMacCorePlayNice;
    unsigned long macOutputStreamFlags = paMacCorePlayNice;
    SInt32 const *inChannelMap = NULL;
    SInt32 const *outChannelMap = NULL;
    unsigned long inChannelMapSize = 0;
    unsigned long outChannelMapSize = 0;

    VVDBUG(("OpenAndSetupOneAudioUnit(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld, requestedFramesPerBuffer=%ld\n",
                inStreamParams  ? inStreamParams->channelCount  : -1,
                inStreamParams  ? inStreamParams->sampleFormat  : -1,
                outStreamParams ? outStreamParams->channelCount : -1,
                outStreamParams ? outStreamParams->sampleFormat : -1,
                requestedFramesPerBuffer ));

    /* -- handle the degenerate case  -- */
    if( !inStreamParams && !outStreamParams ) {
       *audioUnit = NULL;
       *audioDevice = kAudioDeviceUnknown;
       return paNoError;
    }

    /* -- get the user's api specific info, if they set any -- */
    if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo )
    {
       macInputStreamFlags=
            ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
                  ->flags;
       inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
                  ->channelMap;
       inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
                  ->channelMapSize;
    }
    if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo )
    {
       macOutputStreamFlags=
            ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
                  ->flags;
       outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
                  ->channelMap;
       outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
                  ->channelMapSize; 
    }
    /* Override user's flags here, if desired for testing. */

    /*
     * The HAL AU is a Mac OS style "component".
     * the first few steps deal with that.
     * Later steps work on a combination of Mac OS
     * components and the slightly lower level
     * HAL.
     */

    /* -- describe the output type AudioUnit -- */
    /*  Note: for the default AudioUnit, we could use the
     *  componentSubType value kAudioUnitSubType_DefaultOutput;
     *  but I don't think that's relevant here.
     */
    desc.componentType         = kAudioUnitType_Output;
    desc.componentSubType      = kAudioUnitSubType_HALOutput;
    desc.componentManufacturer = kAudioUnitManufacturer_Apple;
    desc.componentFlags        = 0;
    desc.componentFlagsMask    = 0;
    /* -- find the component -- */
    comp = FindNextComponent( NULL, &desc );
    if( !comp )
    {
       DBUG( ( "AUHAL component not found." ) );
       *audioUnit = NULL;
       *audioDevice = kAudioDeviceUnknown;
       return paUnanticipatedHostError;
    }
    /* -- open it -- */
    result = OpenAComponent( comp, audioUnit );
    if( result )
    {
       DBUG( ( "Failed to open AUHAL component." ) );
       *audioUnit = NULL;
       *audioDevice = kAudioDeviceUnknown;
       return ERR( result );
    }
    /* -- prepare a little error handling logic / hackery -- */
#define ERR_WRAP(mac_err) do { result = mac_err ; line = __LINE__ ; if ( result != noErr ) goto error ; } while(0)

    /* -- if there is input, we have to explicitly enable input -- */
    if( inStreamParams )
    {
       UInt32 enableIO = 1;
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                 kAudioOutputUnitProperty_EnableIO,
                 kAudioUnitScope_Input,
                 INPUT_ELEMENT,
                 &enableIO,
                 sizeof(enableIO) ) );
    }
    /* -- if there is no output, we must explicitly disable output -- */
    if( !outStreamParams )
    {
       UInt32 enableIO = 0;
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                 kAudioOutputUnitProperty_EnableIO,
                 kAudioUnitScope_Output,
                 OUTPUT_ELEMENT,
                 &enableIO,
                 sizeof(enableIO) ) );
    }

    /* -- set the devices -- */
    /* make sure input and output are the same device if we are doing input and
       output. */
    if( inStreamParams && outStreamParams )
    {
       assert( outStreamParams->device == inStreamParams->device );
    }
    if( inStreamParams )
    {
       *audioDevice = auhalHostApi->devIds[inStreamParams->device] ;
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                    kAudioOutputUnitProperty_CurrentDevice,
                    kAudioUnitScope_Global,
                    INPUT_ELEMENT,
                    audioDevice,
                    sizeof(AudioDeviceID) ) );
    }
    if( outStreamParams && outStreamParams != inStreamParams )
    {
       *audioDevice = auhalHostApi->devIds[outStreamParams->device] ;
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                    kAudioOutputUnitProperty_CurrentDevice,
                    kAudioUnitScope_Global,
                    OUTPUT_ELEMENT,
                    audioDevice,
                    sizeof(AudioDeviceID) ) );
    }
    /* -- add listener for dropouts -- */
    result = AudioDeviceAddPropertyListener( *audioDevice,
                                             0,
                                             outStreamParams ? false : true,
                                             kAudioDeviceProcessorOverload,
                                             xrunCallback,
                                             addToXRunListenerList( (void *)stream ) ) ;
    if( result == kAudioHardwareIllegalOperationError ) {
       // -- already registered, we're good
    } else {
       // -- not already registered, just check for errors
       ERR_WRAP( result );
    }
    /* -- listen for stream start and stop -- */
    ERR_WRAP( AudioUnitAddPropertyListener( *audioUnit,
                                            kAudioOutputUnitProperty_IsRunning,
                                            startStopCallback,
                                            (void *)stream ) );

    /* -- set format -- */
    bzero( &desiredFormat, sizeof(desiredFormat) );
    desiredFormat.mFormatID         = kAudioFormatLinearPCM ;
    desiredFormat.mFormatFlags      = kAudioFormatFlagsNativeFloatPacked;
    desiredFormat.mFramesPerPacket  = 1;
    desiredFormat.mBitsPerChannel   = sizeof( float ) * 8;

    result = 0;
    /*  set device format first, but only touch the device if the user asked */
    if( inStreamParams ) {
       /*The callback never calls back if we don't set the FPB */
       /*This seems wierd, because I would think setting anything on the device
         would be disruptive.*/
       paResult = setBestFramesPerBuffer( *audioDevice, FALSE,
                                          requestedFramesPerBuffer,
                                          actualInputFramesPerBuffer );
       if( paResult ) goto error;
       if( macInputStreamFlags & paMacCoreChangeDeviceParameters ) {
          bool requireExact;
          requireExact=macInputStreamFlags & paMacCoreFailIfConversionRequired;
          paResult = setBestSampleRateForDevice( *audioDevice, FALSE,
                                                 requireExact, sampleRate );
          if( paResult ) goto error;
       }
       if( actualInputFramesPerBuffer && actualOutputFramesPerBuffer )
          *actualOutputFramesPerBuffer = *actualInputFramesPerBuffer ;
    }
    if( outStreamParams && !inStreamParams ) {
       /*The callback never calls back if we don't set the FPB */
       /*This seems wierd, because I would think setting anything on the device
         would be disruptive.*/
       paResult = setBestFramesPerBuffer( *audioDevice, TRUE,
                                          requestedFramesPerBuffer,
                                          actualOutputFramesPerBuffer );
       if( paResult ) goto error;
       if( macOutputStreamFlags & paMacCoreChangeDeviceParameters ) {
          bool requireExact;
          requireExact=macOutputStreamFlags & paMacCoreFailIfConversionRequired;
          paResult = setBestSampleRateForDevice( *audioDevice, TRUE,
                                                 requireExact, sampleRate );
          if( paResult ) goto error;
       }
    }

    /* -- set the quality of the output converter -- */
    if( outStreamParams ) {
       UInt32 value = kAudioConverterQuality_Max;
       switch( macOutputStreamFlags & 0x0700 ) {
       case 0x0100: /*paMacCore_ConversionQualityMin:*/
          value=kRenderQuality_Min;
          break;
       case 0x0200: /*paMacCore_ConversionQualityLow:*/
          value=kRenderQuality_Low;
          break;
       case 0x0300: /*paMacCore_ConversionQualityMedium:*/
          value=kRenderQuality_Medium;
          break;
       case 0x0400: /*paMacCore_ConversionQualityHigh:*/
          value=kRenderQuality_High;
          break;
       }
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                    kAudioUnitProperty_RenderQuality,
                    kAudioUnitScope_Global,
                    OUTPUT_ELEMENT,
                    &value,
                    sizeof(value) ) );
    }
    /* now set the format on the Audio Units. */
    if( outStreamParams )
    {
       desiredFormat.mSampleRate    =sampleRate;
       desiredFormat.mBytesPerPacket=sizeof(float)*outStreamParams->channelCount;
       desiredFormat.mBytesPerFrame =sizeof(float)*outStreamParams->channelCount;
       desiredFormat.mChannelsPerFrame = outStreamParams->channelCount;
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                            kAudioUnitProperty_StreamFormat,
                            kAudioUnitScope_Input,
                            OUTPUT_ELEMENT,
                            &desiredFormat,
                            sizeof(AudioStreamBasicDescription) ) );
    }
    if( inStreamParams )
    {
       AudioStreamBasicDescription sourceFormat;
       UInt32 size = sizeof( AudioStreamBasicDescription );

       /* keep the sample rate of the device, or we confuse AUHAL */
       ERR_WRAP( AudioUnitGetProperty( *audioUnit,
                            kAudioUnitProperty_StreamFormat,
                            kAudioUnitScope_Input,
                            INPUT_ELEMENT,
                            &sourceFormat,
                            &size ) );
       desiredFormat.mSampleRate = sourceFormat.mSampleRate;
       desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
       desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
       desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                            kAudioUnitProperty_StreamFormat,
                            kAudioUnitScope_Output,
                            INPUT_ELEMENT,
                            &desiredFormat,
                            sizeof(AudioStreamBasicDescription) ) );
    }
    /* set the maximumFramesPerSlice */
    /* not doing this causes real problems
       (eg. the callback might not be called). The idea of setting both this
       and the frames per buffer on the device is that we'll be most likely
       to actually get the frame size we requested in the callback with the
       minimum latency. */
    if( outStreamParams ) {
       UInt32 size = sizeof( *actualOutputFramesPerBuffer );
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                            kAudioUnitProperty_MaximumFramesPerSlice,
                            kAudioUnitScope_Input,
                            OUTPUT_ELEMENT,
                            actualOutputFramesPerBuffer,
                            sizeof(*actualOutputFramesPerBuffer) ) );
       ERR_WRAP( AudioUnitGetProperty( *audioUnit,
                            kAudioUnitProperty_MaximumFramesPerSlice,
                            kAudioUnitScope_Global,
                            OUTPUT_ELEMENT,
                            actualOutputFramesPerBuffer,
                            &size ) );
    }
    if( inStreamParams ) {
       /*UInt32 size = sizeof( *actualInputFramesPerBuffer );*/
       ERR_WRAP( AudioUnitSetProperty( *audioUnit,
                            kAudioUnitProperty_MaximumFramesPerSlice,
                            kAudioUnitScope_Output,
                            INPUT_ELEMENT,
                            actualInputFramesPerBuffer,
                            sizeof(*actualInputFramesPerBuffer) ) );
/* Don't know why this causes problems
       ERR_WRAP( AudioUnitGetProperty( *audioUnit,
                            kAudioUnitProperty_MaximumFramesPerSlice,
                            kAudioUnitScope_Global, //Output,
                            INPUT_ELEMENT,
                            actualInputFramesPerBuffer,
                            &size ) );
*/
    }

    /* -- if we have input, we may need to setup an SR converter -- */
    /* even if we got the sample rate we asked for, we need to do
       the conversion in case another program changes the underlying SR. */
    /* FIXME: I think we need to monitor stream and change the converter if the incoming format changes. */
    if( inStreamParams ) {
       AudioStreamBasicDescription desiredFormat;
       AudioStreamBasicDescription sourceFormat;
       UInt32 sourceSize = sizeof( sourceFormat );
       bzero( &desiredFormat, sizeof(desiredFormat) );
       desiredFormat.mSampleRate       = sampleRate;
       desiredFormat.mFormatID         = kAudioFormatLinearPCM ;
       desiredFormat.mFormatFlags      = kAudioFormatFlagsNativeFloatPacked;
       desiredFormat.mFramesPerPacket  = 1;
       desiredFormat.mBitsPerChannel   = sizeof( float ) * 8;
       desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
       desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
       desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;

       /* get the source format */
       ERR_WRAP( AudioUnitGetProperty(
                         *audioUnit,
                         kAudioUnitProperty_StreamFormat,
                         kAudioUnitScope_Output,
                         INPUT_ELEMENT,
                         &sourceFormat,
                         &sourceSize ) );

       if( desiredFormat.mSampleRate != sourceFormat.mSampleRate )
       {
          UInt32 value = kAudioConverterQuality_Max;
          switch( macInputStreamFlags & 0x0700 ) {
          case 0x0100: /*paMacCore_ConversionQualityMin:*/
             value=kAudioConverterQuality_Min;
             break;
          case 0x0200: /*paMacCore_ConversionQualityLow:*/
             value=kAudioConverterQuality_Low;
             break;
          case 0x0300: /*paMacCore_ConversionQualityMedium:*/
             value=kAudioConverterQuality_Medium;
             break;
          case 0x0400: /*paMacCore_ConversionQualityHigh:*/
             value=kAudioConverterQuality_High;
             break;
          }
          VDBUG(( "Creating sample rate converter for input"
                  " to convert from %g to %g\n",
                  (float)sourceFormat.mSampleRate,
                  (float)desiredFormat.mSampleRate ) );
          /* create our converter */
          ERR_WRAP( AudioConverterNew( 
                             &sourceFormat,
                             &desiredFormat,
                             srConverter ) );
          /* Set quality */
          ERR_WRAP( AudioConverterSetProperty(
                             *srConverter,
                             kAudioConverterSampleRateConverterQuality,
                             sizeof( value ),
                             &value ) );
       }
    }
    /* -- set IOProc (callback) -- */
    callbackKey = outStreamParams ? kAudioUnitProperty_SetRenderCallback
                                  : kAudioOutputUnitProperty_SetInputCallback ;
    rcbs.inputProc = AudioIOProc;
    rcbs.inputProcRefCon = refCon;
    ERR_WRAP( AudioUnitSetProperty(
                               *audioUnit,
                               callbackKey,
                               kAudioUnitScope_Output,
                               outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT,
                               &rcbs,
                               sizeof(rcbs)) );

    if( inStreamParams && outStreamParams && *srConverter )
           ERR_WRAP( AudioUnitSetProperty(
                               *audioUnit,
                               kAudioOutputUnitProperty_SetInputCallback,
                               kAudioUnitScope_Output,
                               INPUT_ELEMENT,
                               &rcbs,
                               sizeof(rcbs)) );

    /* channel mapping. */
    if(inChannelMap)
    {
        UInt32 mapSize = inChannelMapSize *sizeof(SInt32);

        //for each channel of desired input, map the channel from
        //the device's output channel.
        ERR_WRAP( AudioUnitSetProperty(*audioUnit,
                                kAudioOutputUnitProperty_ChannelMap,
                                kAudioUnitScope_Output,
                                INPUT_ELEMENT,
                                inChannelMap,
                                mapSize));
    }
    if(outChannelMap)
    {
        UInt32 mapSize = outChannelMapSize *sizeof(SInt32);

        //for each channel of desired output, map the channel from
        //the device's output channel.
        ERR_WRAP(AudioUnitSetProperty(*audioUnit,
                                kAudioOutputUnitProperty_ChannelMap,
                                kAudioUnitScope_Output,
                                OUTPUT_ELEMENT,
                                outChannelMap,
                                mapSize));
    }
    /* initialize the audio unit */
    ERR_WRAP( AudioUnitInitialize(*audioUnit) );

    if( inStreamParams && outStreamParams )
1550 1551 1552
    {
        VDBUG( ("Opened device %ld for input and output.\n", *audioDevice ) );
    }
bjornroche's avatar
bjornroche committed
1553
    else if( inStreamParams )
1554 1555 1556
    {
        VDBUG( ("Opened device %ld for input.\n", *audioDevice ) );
    }
bjornroche's avatar
bjornroche committed
1557
    else if( outStreamParams )
1558 1559 1560
    {
        VDBUG( ("Opened device %ld for output.\n", *audioDevice ) );
    }
bjornroche's avatar
bjornroche committed
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
    return paNoError;
#undef ERR_WRAP

    error:
       CloseComponent( *audioUnit );
       *audioUnit = NULL;
       if( result )
          return PaMacCore_SetError( result, line, 1 );
       return paResult;
}

1572 1573
/* =================================================================================================== */

1574
static UInt32 CalculateOptimalBufferSize( PaMacAUHAL *auhalHostApi,
1575 1576 1577 1578
                                  const PaStreamParameters *inputParameters,
                                  const PaStreamParameters *outputParameters,
                                  UInt32 fixedInputLatency,
                                  UInt32 fixedOutputLatency,
1579 1580
                                  double sampleRate,
                                  UInt32 requestedFramesPerBuffer )
1581
{
1582
    UInt32 suggested = 0;  
1583 1584 1585 1586 1587 1588 1589 1590
    // Use maximum of suggested input and output latencies.
    if( inputParameters )
    {
        UInt32 suggestedLatencyFrames = inputParameters->suggestedLatency * sampleRate;
        // Calculate a buffer size assuming we are double buffered.
        SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedInputLatency;
        // Prevent negative latency.
        variableLatencyFrames = MAX( variableLatencyFrames, 0 );       
1591
        suggested = MAX( suggested, (UInt32) variableLatencyFrames );
1592 1593 1594 1595 1596 1597
    }
    if( outputParameters )
    {        
        UInt32 suggestedLatencyFrames = outputParameters->suggestedLatency * sampleRate;
        SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedOutputLatency;
        variableLatencyFrames = MAX( variableLatencyFrames, 0 );
1598
        suggested = MAX( suggested, (UInt32) variableLatencyFrames );
1599 1600 1601
    }
    
    VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n",
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
            suggested ) );
    
    if( requestedFramesPerBuffer != paFramesPerBufferUnspecified )
    {
        if( suggested > (requestedFramesPerBuffer + 1) )
        {
            // If the user asks for higher latency than the requested buffer size would provide
            // then put multiple user buffers in one host buffer.
            UInt32 userBuffersPerHostBuffer = (suggested + (requestedFramesPerBuffer - 1)) / requestedFramesPerBuffer;
            suggested = userBuffersPerHostBuffer * requestedFramesPerBuffer;
        }
    }
1614 1615 1616 1617 1618 1619
    
    // Clip to the capabilities of the device.
    if( inputParameters )
    {
        ClipToDeviceBufferSize( auhalHostApi->devIds[inputParameters->device],
                               true, // In the old code isInput was false!
1620
                               suggested, &suggested );
1621 1622 1623 1624
    }
    if( outputParameters )
    {
        ClipToDeviceBufferSize( auhalHostApi->devIds[outputParameters->device],
1625
                               false, suggested, &suggested );
1626
    }
1627
    VDBUG(("After querying hardware, setting block size to %ld.\n", suggested));
1628

1629
    return suggested;
1630 1631 1632
}

/* =================================================================================================== */
bjornroche's avatar
bjornroche committed
1633 1634 1635 1636 1637 1638
/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                           PaStream** s,
                           const PaStreamParameters *inputParameters,
                           const PaStreamParameters *outputParameters,
                           double sampleRate,
1639
                           unsigned long requestedFramesPerBuffer,
bjornroche's avatar
bjornroche committed
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
                           PaStreamFlags streamFlags,
                           PaStreamCallback *streamCallback,
                           void *userData )
{
    PaError result = paNoError;
    PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
    PaMacCoreStream *stream = 0;
    int inputChannelCount, outputChannelCount;
    PaSampleFormat inputSampleFormat, outputSampleFormat;
    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
1650 1651 1652 1653 1654
    UInt32 fixedInputLatency = 0;
    UInt32 fixedOutputLatency = 0;
    // Accumulate contributions to latency in these variables.
    UInt32 inputLatencyFrames = 0;
    UInt32 outputLatencyFrames = 0;
1655
    UInt32 suggestedLatencyFramesPerBuffer = requestedFramesPerBuffer;
1656
    
bjornroche's avatar
bjornroche committed
1657 1658 1659 1660 1661 1662
    VVDBUG(("OpenStream(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld SR=%g, FPB=%ld\n",
                inputParameters  ? inputParameters->channelCount  : -1,
                inputParameters  ? inputParameters->sampleFormat  : -1,
                outputParameters ? outputParameters->channelCount : -1,
                outputParameters ? outputParameters->sampleFormat : -1,
                (float) sampleRate,
1663
                requestedFramesPerBuffer ));
bjornroche's avatar
bjornroche committed
1664
    VDBUG( ("Opening Stream.\n") );
1665
	
1666
    /* These first few bits of code are from paSkeleton with few modifications. */
bjornroche's avatar
bjornroche committed
1667 1668 1669 1670 1671
    if( inputParameters )
    {
        inputChannelCount = inputParameters->channelCount;
        inputSampleFormat = inputParameters->sampleFormat;

1672
		/* @todo Blocking read/write on Mac is not yet supported. */
1673
		if( !streamCallback && inputSampleFormat & paNonInterleaved )
1674 1675 1676 1677
		{
			return paSampleFormatNotSupported;
		}
		
bjornroche's avatar
bjornroche committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
        /* unless alternate device specification is supported, reject the use of
            paUseHostApiSpecificDeviceSpecification */

        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
            return paInvalidDevice;

        /* check that input device can support inputChannelCount */
        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
            return paInvalidChannelCount;

        /* Host supports interleaved float32 */
        hostInputSampleFormat = paFloat32;
    }
    else
    {
        inputChannelCount = 0;
        inputSampleFormat = hostInputSampleFormat = paFloat32; /* Surpress 'uninitialised var' warnings. */
    }

    if( outputParameters )
    {
        outputChannelCount = outputParameters->channelCount;
        outputSampleFormat = outputParameters->sampleFormat;
        
1702
		/* @todo Blocking read/write on Mac is not yet supported. */
1703
		if( !streamCallback && outputSampleFormat & paNonInterleaved )
1704 1705 1706 1707
		{
			return paSampleFormatNotSupported;
		}
		
bjornroche's avatar
bjornroche committed
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
        /* unless alternate device specification is supported, reject the use of
            paUseHostApiSpecificDeviceSpecification */

        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
            return paInvalidDevice;

        /* check that output device can support inputChannelCount */
        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
            return paInvalidChannelCount;

        /* Host supports interleaved float32 */
        hostOutputSampleFormat = paFloat32;
    }
    else
    {
        outputChannelCount = 0;
        outputSampleFormat = hostOutputSampleFormat = paFloat32; /* Surpress 'uninitialized var' warnings. */
    }

    /* validate platform specific flags */
    if( (streamFlags & paPlatformSpecificFlags) != 0 )
        return paInvalidFlag; /* unexpected platform specific flag */

    stream = (PaMacCoreStream*)PaUtil_AllocateMemory( sizeof(PaMacCoreStream) );
    if( !stream )
    {
        result = paInsufficientMemory;
        goto error;
    }

    /* If we fail after this point, we my be left in a bad state, with
       some data structures setup and others not. So, first thing we
       do is initialize everything so that if we fail, we know what hasn't
       been touched.
     */

    stream->inputAudioBufferList.mBuffers[0].mData = NULL;
    stream->inputRingBuffer.buffer = NULL;
    bzero( &stream->blio, sizeof( PaMacBlio ) );
/*
    stream->blio.inputRingBuffer.buffer = NULL;
    stream->blio.outputRingBuffer.buffer = NULL;
    stream->blio.inputSampleFormat = inputParameters?inputParameters->sampleFormat:0;
    stream->blio.inputSampleSize = computeSampleSizeFromFormat(stream->blio.inputSampleFormat);
    stream->blio.outputSampleFormat=outputParameters?outputParameters->sampleFormat:0;
    stream->blio.outputSampleSize = computeSampleSizeFromFormat(stream->blio.outputSampleFormat);
*/
    stream->inputSRConverter = NULL;
    stream->inputUnit = NULL;
    stream->outputUnit = NULL;
    stream->inputFramesPerBuffer = 0;
    stream->outputFramesPerBuffer = 0;
    stream->bufferProcessorIsInitialized = FALSE;
1761
	stream->timingInformationMutexIsInitialized = 0;
bjornroche's avatar
bjornroche committed
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778

    /* assert( streamCallback ) ; */ /* only callback mode is implemented */
    if( streamCallback )
    {
        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
                                        &auhalHostApi->callbackStreamInterface,
                                        streamCallback, userData );
    }
    else
    {
        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
                                        &auhalHostApi->blockingStreamInterface,
                                        BlioCallback, &stream->blio );
    }

    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );

1779 1780 1781 1782 1783
    
    if( inputParameters )
    {
        CalculateFixedDeviceLatency( auhalHostApi->devIds[inputParameters->device], true, &fixedInputLatency );
        inputLatencyFrames += fixedInputLatency;
bjornroche's avatar
bjornroche committed
1784
    }
1785 1786 1787 1788 1789 1790 1791
    if( outputParameters )
    {        
        CalculateFixedDeviceLatency( auhalHostApi->devIds[outputParameters->device], false, &fixedOutputLatency );
        outputLatencyFrames += fixedOutputLatency;

    }
    
1792 1793 1794 1795
    suggestedLatencyFramesPerBuffer = CalculateOptimalBufferSize( auhalHostApi, inputParameters, outputParameters,
                                                                 fixedInputLatency, fixedOutputLatency,
                                                                 sampleRate, requestedFramesPerBuffer );
    if( requestedFramesPerBuffer == paFramesPerBufferUnspecified )
1796
	{
1797
        requestedFramesPerBuffer = suggestedLatencyFramesPerBuffer;
1798
    }
bjornroche's avatar
bjornroche committed
1799 1800 1801 1802 1803 1804 1805 1806 1807

    /* -- Now we actually open and setup streams. -- */
    if( inputParameters && outputParameters && outputParameters->device == inputParameters->device )
    { /* full duplex. One device. */
       UInt32 inputFramesPerBuffer  = (UInt32) stream->inputFramesPerBuffer;
       UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
       result = OpenAndSetupOneAudioUnit( stream,
                                          inputParameters,
                                          outputParameters,
1808
                                          suggestedLatencyFramesPerBuffer,
bjornroche's avatar
bjornroche committed
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
                                          &inputFramesPerBuffer,
                                          &outputFramesPerBuffer,
                                          auhalHostApi,
                                          &(stream->inputUnit),
                                          &(stream->inputSRConverter),
                                          &(stream->inputDevice),
                                          sampleRate,
                                          stream );
       stream->inputFramesPerBuffer = inputFramesPerBuffer;
       stream->outputFramesPerBuffer = outputFramesPerBuffer;
       stream->outputUnit = stream->inputUnit;
       stream->outputDevice = stream->inputDevice;
       if( result != paNoError )
           goto error;
    }
    else
    { /* full duplex, different devices OR simplex */
       UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
       UInt32 inputFramesPerBuffer  = (UInt32) stream->inputFramesPerBuffer;
       result = OpenAndSetupOneAudioUnit( stream,
                                          NULL,
                                          outputParameters,
1831
                                          suggestedLatencyFramesPerBuffer,
bjornroche's avatar
bjornroche committed
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
                                          NULL,
                                          &outputFramesPerBuffer,
                                          auhalHostApi,
                                          &(stream->outputUnit),
                                          NULL,
                                          &(stream->outputDevice),
                                          sampleRate,
                                          stream );
       if( result != paNoError )
           goto error;
       result = OpenAndSetupOneAudioUnit( stream,
                                          inputParameters,
                                          NULL,
1845
                                          suggestedLatencyFramesPerBuffer,
bjornroche's avatar
bjornroche committed
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
                                          &inputFramesPerBuffer,
                                          NULL,
                                          auhalHostApi,
                                          &(stream->inputUnit),
                                          &(stream->inputSRConverter),
                                          &(stream->inputDevice),
                                          sampleRate,
                                          stream );
       if( result != paNoError )
           goto error;
       stream->inputFramesPerBuffer = inputFramesPerBuffer;
       stream->outputFramesPerBuffer = outputFramesPerBuffer;
    }
1859 1860 1861 1862
    
    inputLatencyFrames += stream->inputFramesPerBuffer;
    outputLatencyFrames += stream->outputFramesPerBuffer;
    
bjornroche's avatar
bjornroche committed
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    if( stream->inputUnit ) {
       const size_t szfl = sizeof(float);
       /* setup the AudioBufferList used for input */
       bzero( &stream->inputAudioBufferList, sizeof( AudioBufferList ) );
       stream->inputAudioBufferList.mNumberBuffers = 1;
       stream->inputAudioBufferList.mBuffers[0].mNumberChannels
                 = inputChannelCount;
       stream->inputAudioBufferList.mBuffers[0].mDataByteSize
                 = stream->inputFramesPerBuffer*inputChannelCount*szfl;