Skip to content
Snippets Groups Projects
RtMidi.cpp 91.6 KiB
Newer Older
  • Learn to ignore specific revisions
  • SeeLook's avatar
    SeeLook committed
    /**********************************************************************/
    /*! \class RtMidi
        \brief An abstract base class for realtime MIDI input/output.
    
        This class implements some common functionality for the realtime
        MIDI input/output subclasses RtMidiIn and RtMidiOut.
    
        RtMidi WWW site: http://music.mcgill.ca/~gary/rtmidi/
    
        RtMidi: realtime MIDI i/o C++ classes
    
        Copyright (c) 2003-2014 Gary P. Scavone
    
    SeeLook's avatar
    SeeLook committed
    
        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.
    
        Any person wishing to distribute modifications to the Software is
        asked to send the modifications to the original developer so that
        they can be incorporated into the canonical version.  This is,
        however, not a binding provision of this license.
    
        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.
    */
    /**********************************************************************/
    
    #include "RtMidi.h"
    #include <sstream>
    
    //*********************************************************************//
    //  RtMidi Definitions
    //*********************************************************************//
    
    
    RtMidi :: RtMidi()
      : rtapi_(0)
    {
    }
    
    RtMidi :: ~RtMidi()
    {
      if ( rtapi_ )
        delete rtapi_;
      rtapi_ = 0;
    }
    
    std::string RtMidi :: getVersion( void ) throw()
    {
      return std::string( RTMIDI_VERSION );
    }
    
    
    SeeLook's avatar
    SeeLook committed
    void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw()
    {
      apis.clear();
    
      // The order here will control the order of RtMidi's API search in
      // the constructor.
    #if defined(__MACOSX_CORE__)
      apis.push_back( MACOSX_CORE );
    #endif
    #if defined(__LINUX_ALSA__)
      apis.push_back( LINUX_ALSA );
    #endif
    #if defined(__UNIX_JACK__)
      apis.push_back( UNIX_JACK );
    #endif
    #if defined(__WINDOWS_MM__)
      apis.push_back( WINDOWS_MM );
    #endif
    #if defined(__RTMIDI_DUMMY__)
      apis.push_back( RTMIDI_DUMMY );
    #endif
    }
    
    //*********************************************************************//
    //  RtMidiIn Definitions
    //*********************************************************************//
    
    void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
    {
      if ( rtapi_ )
        delete rtapi_;
      rtapi_ = 0;
    
    #if defined(__UNIX_JACK__)
      if ( api == UNIX_JACK )
        rtapi_ = new MidiInJack( clientName, queueSizeLimit );
    #endif
    #if defined(__LINUX_ALSA__)
      if ( api == LINUX_ALSA )
        rtapi_ = new MidiInAlsa( clientName, queueSizeLimit );
    #endif
    #if defined(__WINDOWS_MM__)
      if ( api == WINDOWS_MM )
        rtapi_ = new MidiInWinMM( clientName, queueSizeLimit );
    #endif
    #if defined(__MACOSX_CORE__)
      if ( api == MACOSX_CORE )
        rtapi_ = new MidiInCore( clientName, queueSizeLimit );
    #endif
    #if defined(__RTMIDI_DUMMY__)
      if ( api == RTMIDI_DUMMY )
        rtapi_ = new MidiInDummy( clientName, queueSizeLimit );
    #endif
    }
    
    RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit )
    
    SeeLook's avatar
    SeeLook committed
    {
      if ( api != UNSPECIFIED ) {
        // Attempt to open the specified API.
        openMidiApi( api, clientName, queueSizeLimit );
        if ( rtapi_ ) return;
    
    
        // No compiled support for specified API value.  Issue a warning
        // and continue as if no API was specified.
        std::cerr << "\nRtMidiIn: no compiled support for specified API argument!\n\n" << std::endl;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Iterate through the compiled APIs and return as soon as we find
      // one with at least one port or we reach the end of the list.
      std::vector< RtMidi::Api > apis;
      getCompiledApi( apis );
      for ( unsigned int i=0; i<apis.size(); i++ ) {
        openMidiApi( apis[i], clientName, queueSizeLimit );
        if ( rtapi_->getPortCount() ) break;
      }
    
      if ( rtapi_ ) return;
    
      // It should not be possible to get here because the preprocessor
      // definition __RTMIDI_DUMMY__ is automatically defined if no
      // API-specific definitions are passed to the compiler. But just in
    
      // case something weird happens, we'll throw an error.
      std::string errorText = "RtMidiIn: no compiled API support found ... critical error!!";
      throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
    
    SeeLook's avatar
    SeeLook committed
    }
    
    RtMidiIn :: ~RtMidiIn() throw()
    {
    }
    
    
    //*********************************************************************//
    //  RtMidiOut Definitions
    //*********************************************************************//
    
    void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string clientName )
    {
      if ( rtapi_ )
        delete rtapi_;
      rtapi_ = 0;
    
    #if defined(__UNIX_JACK__)
      if ( api == UNIX_JACK )
        rtapi_ = new MidiOutJack( clientName );
    #endif
    #if defined(__LINUX_ALSA__)
      if ( api == LINUX_ALSA )
        rtapi_ = new MidiOutAlsa( clientName );
    #endif
    #if defined(__WINDOWS_MM__)
      if ( api == WINDOWS_MM )
        rtapi_ = new MidiOutWinMM( clientName );
    #endif
    #if defined(__MACOSX_CORE__)
      if ( api == MACOSX_CORE )
        rtapi_ = new MidiOutCore( clientName );
    #endif
    #if defined(__RTMIDI_DUMMY__)
      if ( api == RTMIDI_DUMMY )
        rtapi_ = new MidiOutDummy( clientName );
    #endif
    }
    
    RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string clientName )
    {
      if ( api != UNSPECIFIED ) {
        // Attempt to open the specified API.
        openMidiApi( api, clientName );
        if ( rtapi_ ) return;
    
    
        // No compiled support for specified API value.  Issue a warning
        // and continue as if no API was specified.
        std::cerr << "\nRtMidiOut: no compiled support for specified API argument!\n\n" << std::endl;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Iterate through the compiled APIs and return as soon as we find
      // one with at least one port or we reach the end of the list.
      std::vector< RtMidi::Api > apis;
      getCompiledApi( apis );
      for ( unsigned int i=0; i<apis.size(); i++ ) {
        openMidiApi( apis[i], clientName );
        if ( rtapi_->getPortCount() ) break;
      }
    
      if ( rtapi_ ) return;
    
      // It should not be possible to get here because the preprocessor
      // definition __RTMIDI_DUMMY__ is automatically defined if no
      // API-specific definitions are passed to the compiler. But just in
    
      // case something weird happens, we'll thrown an error.
      std::string errorText = "RtMidiOut: no compiled API support found ... critical error!!";
      throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
    
    SeeLook's avatar
    SeeLook committed
    }
    
    RtMidiOut :: ~RtMidiOut() throw()
    {
    
    }
    
    //*********************************************************************//
    //  Common MidiApi Definitions
    //*********************************************************************//
    
    MidiApi :: MidiApi( void )
      : apiData_( 0 ), connected_( false ), errorCallback_(0)
    {
    }
    
    MidiApi :: ~MidiApi( void )
    {
    }
    
    void MidiApi :: setErrorCallback( RtMidiErrorCallback errorCallback )
    {
        errorCallback_ = errorCallback;
    }
    
    void MidiApi :: error( RtMidiError::Type type, std::string errorString )
    {
      if ( errorCallback_ ) {
        static bool firstErrorOccured = false;
    
        if ( firstErrorOccured )
          return;
    
        firstErrorOccured = true;
        const std::string errorMessage = errorString;
    
        errorCallback_( type, errorMessage );
        firstErrorOccured = false;
        return;
      }
    
      if ( type == RtMidiError::WARNING ) {
        std::cerr << '\n' << errorString << "\n\n";
      }
      else if ( type == RtMidiError::DEBUG_WARNING ) {
    #if defined(__RTMIDI_DEBUG__)
        std::cerr << '\n' << errorString << "\n\n";
    #endif
      }
      else {
        std::cerr << '\n' << errorString << "\n\n";
        throw RtMidiError( errorString, type );
      }
    
    SeeLook's avatar
    SeeLook committed
    }
    
    //*********************************************************************//
    //  Common MidiInApi Definitions
    //*********************************************************************//
    
    MidiInApi :: MidiInApi( unsigned int queueSizeLimit )
    
    SeeLook's avatar
    SeeLook committed
    {
      // Allocate the MIDI queue.
      inputData_.queue.ringSize = queueSizeLimit;
      if ( inputData_.queue.ringSize > 0 )
        inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ];
    }
    
    MidiInApi :: ~MidiInApi( void )
    {
      // Delete the MIDI queue.
      if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring;
    }
    
    void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData )
    {
      if ( inputData_.usingCallback ) {
        errorString_ = "MidiInApi::setCallback: a callback function is already set!";
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return;
      }
    
      if ( !callback ) {
        errorString_ = "RtMidiIn::setCallback: callback function value is invalid!";
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return;
      }
    
    
      inputData_.userCallback = callback;
    
    SeeLook's avatar
    SeeLook committed
      inputData_.userData = userData;
      inputData_.usingCallback = true;
    }
    
    void MidiInApi :: cancelCallback()
    {
      if ( !inputData_.usingCallback ) {
        errorString_ = "RtMidiIn::cancelCallback: no callback function was set!";
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return;
      }
    
      inputData_.userCallback = 0;
      inputData_.userData = 0;
      inputData_.usingCallback = false;
    }
    
    void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense )
    {
      inputData_.ignoreFlags = 0;
      if ( midiSysex ) inputData_.ignoreFlags = 0x01;
      if ( midiTime ) inputData_.ignoreFlags |= 0x02;
      if ( midiSense ) inputData_.ignoreFlags |= 0x04;
    }
    
    double MidiInApi :: getMessage( std::vector<unsigned char> *message )
    {
      message->clear();
    
      if ( inputData_.usingCallback ) {
        errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port.";
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return 0.0;
      }
    
      if ( inputData_.queue.size == 0 ) return 0.0;
    
      // Copy queued message to the vector pointer argument and then "pop" it.
      std::vector<unsigned char> *bytes = &(inputData_.queue.ring[inputData_.queue.front].bytes);
      message->assign( bytes->begin(), bytes->end() );
      double deltaTime = inputData_.queue.ring[inputData_.queue.front].timeStamp;
      inputData_.queue.size--;
      inputData_.queue.front++;
      if ( inputData_.queue.front == inputData_.queue.ringSize )
        inputData_.queue.front = 0;
    
      return deltaTime;
    }
    
    //*********************************************************************//
    //  Common MidiOutApi Definitions
    //*********************************************************************//
    
    MidiOutApi :: MidiOutApi( void )
    
    SeeLook's avatar
    SeeLook committed
    {
    }
    
    MidiOutApi :: ~MidiOutApi( void )
    {
    }
    
    // *************************************************** //
    //
    // OS/API-specific methods.
    //
    // *************************************************** //
    
    #if defined(__MACOSX_CORE__)
    
    // The CoreMIDI API is based on the use of a callback function for
    // MIDI input.  We convert the system specific time stamps to delta
    // time values.
    
    // OS-X CoreMIDI header files.
    #include <CoreMIDI/CoreMIDI.h>
    #include <CoreAudio/HostTime.h>
    #include <CoreServices/CoreServices.h>
    
    // A structure to hold variables related to the CoreMIDI API
    // implementation.
    struct CoreMidiData {
      MIDIClientRef client;
      MIDIPortRef port;
      MIDIEndpointRef endpoint;
      MIDIEndpointRef destinationId;
      unsigned long long lastTime;
      MIDISysexSendRequest sysexreq;
    };
    
    //*********************************************************************//
    //  API: OS-X
    //  Class Definitions: MidiInCore
    //*********************************************************************//
    
    
    static void midiInputCallback( const MIDIPacketList *list, void *procRef, void */*srcRef*/ )
    
    SeeLook's avatar
    SeeLook committed
    {
      MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef);
      CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData);
    
      unsigned char status;
      unsigned short nBytes, iByte, size;
      unsigned long long time;
    
      bool& continueSysex = data->continueSysex;
      MidiInApi::MidiMessage& message = data->message;
    
      const MIDIPacket *packet = &list->packet[0];
      for ( unsigned int i=0; i<list->numPackets; ++i ) {
    
        // My interpretation of the CoreMIDI documentation: all message
        // types, except sysex, are complete within a packet and there may
        // be several of them in a single packet.  Sysex messages can be
        // broken across multiple packets and PacketLists but are bundled
        // alone within each packet (these packets do not contain other
        // message types).  If sysex messages are split across multiple
        // MIDIPacketLists, they must be handled by multiple calls to this
        // function.
    
        nBytes = packet->length;
        if ( nBytes == 0 ) continue;
    
        // Calculate time stamp.
    
        if ( data->firstMessage ) {
          message.timeStamp = 0.0;
          data->firstMessage = false;
        }
        else {
          time = packet->timeStamp;
          if ( time == 0 ) { // this happens when receiving asynchronous sysex messages
            time = AudioGetCurrentHostTime();
          }
          time -= apiData->lastTime;
          time = AudioConvertHostTimeToNanos( time );
          if ( !continueSysex )
            message.timeStamp = time * 0.000000001;
        }
        apiData->lastTime = packet->timeStamp;
        if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages
          apiData->lastTime = AudioGetCurrentHostTime();
        }
        //std::cout << "TimeStamp = " << packet->timeStamp << std::endl;
    
        iByte = 0;
        if ( continueSysex ) {
          // We have a continuing, segmented sysex message.
          if ( !( data->ignoreFlags & 0x01 ) ) {
            // If we're not ignoring sysex messages, copy the entire packet.
            for ( unsigned int j=0; j<nBytes; ++j )
              message.bytes.push_back( packet->data[j] );
          }
          continueSysex = packet->data[nBytes-1] != 0xF7;
    
    
          if ( !( data->ignoreFlags & 0x01 ) && !continueSysex ) {
    
    SeeLook's avatar
    SeeLook committed
            // If not a continuing sysex message, invoke the user callback function or queue the message.
            if ( data->usingCallback ) {
              RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
              callback( message.timeStamp, &message.bytes, data->userData );
            }
            else {
              // As long as we haven't reached our queue size limit, push the message.
              if ( data->queue.size < data->queue.ringSize ) {
                data->queue.ring[data->queue.back++] = message;
                if ( data->queue.back == data->queue.ringSize )
                  data->queue.back = 0;
                data->queue.size++;
              }
              else
                std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
            }
            message.bytes.clear();
          }
        }
        else {
          while ( iByte < nBytes ) {
            size = 0;
            // We are expecting that the next byte in the packet is a status byte.
            status = packet->data[iByte];
            if ( !(status & 0x80) ) break;
            // Determine the number of bytes in the MIDI message.
            if ( status < 0xC0 ) size = 3;
            else if ( status < 0xE0 ) size = 2;
            else if ( status < 0xF0 ) size = 3;
            else if ( status == 0xF0 ) {
              // A MIDI sysex
              if ( data->ignoreFlags & 0x01 ) {
                size = 0;
                iByte = nBytes;
              }
              else size = nBytes - iByte;
              continueSysex = packet->data[nBytes-1] != 0xF7;
            }
            else if ( status == 0xF1 ) {
                // A MIDI time code message
               if ( data->ignoreFlags & 0x02 ) {
                size = 0;
                iByte += 2;
               }
               else size = 2;
            }
            else if ( status == 0xF2 ) size = 3;
            else if ( status == 0xF3 ) size = 2;
            else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) {
              // A MIDI timing tick message and we're ignoring it.
              size = 0;
              iByte += 1;
            }
            else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) {
              // A MIDI active sensing message and we're ignoring it.
              size = 0;
              iByte += 1;
            }
            else size = 1;
    
            // Copy the MIDI data to our vector.
            if ( size ) {
              message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] );
              if ( !continueSysex ) {
                // If not a continuing sysex message, invoke the user callback function or queue the message.
                if ( data->usingCallback ) {
                  RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
                  callback( message.timeStamp, &message.bytes, data->userData );
                }
                else {
                  // As long as we haven't reached our queue size limit, push the message.
                  if ( data->queue.size < data->queue.ringSize ) {
                    data->queue.ring[data->queue.back++] = message;
                    if ( data->queue.back == data->queue.ringSize )
                      data->queue.back = 0;
                    data->queue.size++;
                  }
                  else
                    std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
                }
                message.bytes.clear();
              }
              iByte += size;
            }
          }
        }
        packet = MIDIPacketNext(packet);
      }
    }
    
    MidiInCore :: MidiInCore( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit )
    {
      initialize( clientName );
    }
    
    MidiInCore :: ~MidiInCore( void )
    {
      // Close a connection if it exists.
      closePort();
    
      // Cleanup.
      CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
      MIDIClientDispose( data->client );
      if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
      delete data;
    }
    
    void MidiInCore :: initialize( const std::string& clientName )
    {
      // Set up our client.
      MIDIClientRef client;
      OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
      if ( result != noErr ) {
        errorString_ = "MidiInCore::initialize: error creating OS-X MIDI client object.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Save our api-specific connection information.
      CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
      data->client = client;
      data->endpoint = 0;
      apiData_ = (void *) data;
      inputData_.apiData = (void *) data;
    }
    
    void MidiInCore :: openPort( unsigned int portNumber, const std::string portName )
    {
      if ( connected_ ) {
        errorString_ = "MidiInCore::openPort: a valid connection already exists!";
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return;
      }
    
    
      CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
    
    SeeLook's avatar
    SeeLook committed
      unsigned int nSrc = MIDIGetNumberOfSources();
      if (nSrc < 1) {
        errorString_ = "MidiInCore::openPort: no MIDI input sources found!";
    
        error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      if ( portNumber >= nSrc ) {
    
    SeeLook's avatar
    SeeLook committed
        ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
        errorString_ = ost.str();
    
        error( RtMidiError::INVALID_PARAMETER, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      MIDIPortRef port;
      CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
      OSStatus result = MIDIInputPortCreate( data->client, 
                                             CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
                                             midiInputCallback, (void *)&inputData_, &port );
      if ( result != noErr ) {
        MIDIClientDispose( data->client );
        errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Get the desired input source identifier.
      MIDIEndpointRef endpoint = MIDIGetSource( portNumber );
      if ( endpoint == 0 ) {
        MIDIPortDispose( port );
        MIDIClientDispose( data->client );
        errorString_ = "MidiInCore::openPort: error getting MIDI input source reference.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Make the connection.
      result = MIDIPortConnectSource( port, endpoint, NULL );
      if ( result != noErr ) {
        MIDIPortDispose( port );
        MIDIClientDispose( data->client );
        errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Save our api-specific port information.
      data->port = port;
    
      connected_ = true;
    }
    
    void MidiInCore :: openVirtualPort( const std::string portName )
    {
      CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
    
      // Create a virtual MIDI input destination.
      MIDIEndpointRef endpoint;
      OSStatus result = MIDIDestinationCreate( data->client,
                                               CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
                                               midiInputCallback, (void *)&inputData_, &endpoint );
      if ( result != noErr ) {
        errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Save our api-specific connection information.
      data->endpoint = endpoint;
    }
    
    void MidiInCore :: closePort( void )
    {
      if ( connected_ ) {
        CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
        MIDIPortDispose( data->port );
        connected_ = false;
      }
    }
    
    unsigned int MidiInCore :: getPortCount()
    {
    
      CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
    
    SeeLook's avatar
    SeeLook committed
      return MIDIGetNumberOfSources();
    }
    
    // This function was submitted by Douglas Casey Tucker and apparently
    // derived largely from PortMidi.
    CFStringRef EndpointName( MIDIEndpointRef endpoint, bool isExternal )
    {
      CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
      CFStringRef str;
    
      // Begin with the endpoint's name.
      str = NULL;
      MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str );
      if ( str != NULL ) {
        CFStringAppend( result, str );
        CFRelease( str );
      }
    
    
    SeeLook's avatar
    SeeLook committed
      MIDIEndpointGetEntity( endpoint, &entity );
      if ( entity == 0 )
        // probably virtual
        return result;
    
      if ( CFStringGetLength( result ) == 0 ) {
        // endpoint name has zero length -- try the entity
        str = NULL;
        MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str );
        if ( str != NULL ) {
          CFStringAppend( result, str );
          CFRelease( str );
        }
      }
      // now consider the device's name
      MIDIDeviceRef device = 0;
      MIDIEntityGetDevice( entity, &device );
      if ( device == 0 )
        return result;
    
      str = NULL;
      MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str );
      if ( CFStringGetLength( result ) == 0 ) {
          CFRelease( result );
          return str;
      }
      if ( str != NULL ) {
        // if an external device has only one entity, throw away
        // the endpoint name and just use the device name
        if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) {
          CFRelease( result );
          return str;
        } else {
          if ( CFStringGetLength( str ) == 0 ) {
            CFRelease( str );
            return result;
          }
          // does the entity name already start with the device name?
          // (some drivers do this though they shouldn't)
          // if so, do not prepend
            if ( CFStringCompareWithOptions( result, /* endpoint name */
                 str /* device name */,
                 CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) {
            // prepend the device name to the entity name
            if ( CFStringGetLength( result ) > 0 )
              CFStringInsert( result, 0, CFSTR(" ") );
            CFStringInsert( result, 0, str );
          }
          CFRelease( str );
        }
      }
      return result;
    }
    
    // This function was submitted by Douglas Casey Tucker and apparently
    // derived largely from PortMidi.
    static CFStringRef ConnectedEndpointName( MIDIEndpointRef endpoint )
    {
      CFMutableStringRef result = CFStringCreateMutable( NULL, 0 );
      CFStringRef str;
      OSStatus err;
      int i;
    
      // Does the endpoint have connections?
      CFDataRef connections = NULL;
      int nConnected = 0;
      bool anyStrings = false;
      err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections );
      if ( connections != NULL ) {
        // It has connections, follow them
        // Concatenate the names of all connected devices
        nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID);
        if ( nConnected ) {
          const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections));
          for ( i=0; i<nConnected; ++i, ++pid ) {
            MIDIUniqueID id = EndianS32_BtoN( *pid );
            MIDIObjectRef connObject;
            MIDIObjectType connObjectType;
            err = MIDIObjectFindByUniqueID( id, &connObject, &connObjectType );
            if ( err == noErr ) {
              if ( connObjectType == kMIDIObjectType_ExternalSource  ||
                  connObjectType == kMIDIObjectType_ExternalDestination ) {
                // Connected to an external device's endpoint (10.3 and later).
                str = EndpointName( (MIDIEndpointRef)(connObject), true );
              } else {
                // Connected to an external device (10.2) (or something else, catch-
                str = NULL;
                MIDIObjectGetStringProperty( connObject, kMIDIPropertyName, &str );
              }
              if ( str != NULL ) {
                if ( anyStrings )
                  CFStringAppend( result, CFSTR(", ") );
                else anyStrings = true;
                CFStringAppend( result, str );
                CFRelease( str );
              }
            }
          }
        }
        CFRelease( connections );
      }
      if ( anyStrings )
        return result;
    
      // Here, either the endpoint had no connections, or we failed to obtain names 
      return EndpointName( endpoint, false );
    }
    
    std::string MidiInCore :: getPortName( unsigned int portNumber )
    {
      CFStringRef nameRef;
      MIDIEndpointRef portRef;
      char name[128];
    
      std::string stringName;
    
      CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
    
    SeeLook's avatar
    SeeLook committed
      if ( portNumber >= MIDIGetNumberOfSources() ) {
    
    SeeLook's avatar
    SeeLook committed
        ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
        errorString_ = ost.str();
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return stringName;
      }
    
      portRef = MIDIGetSource( portNumber );
      nameRef = ConnectedEndpointName(portRef);
    
      CFStringGetCString( nameRef, name, sizeof(name), CFStringGetSystemEncoding());
    
    SeeLook's avatar
    SeeLook committed
      CFRelease( nameRef );
    
      return stringName = name;
    }
    
    //*********************************************************************//
    //  API: OS-X
    //  Class Definitions: MidiOutCore
    //*********************************************************************//
    
    MidiOutCore :: MidiOutCore( const std::string clientName ) : MidiOutApi()
    {
      initialize( clientName );
    }
    
    MidiOutCore :: ~MidiOutCore( void )
    {
      // Close a connection if it exists.
      closePort();
    
      // Cleanup.
      CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
      MIDIClientDispose( data->client );
      if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
      delete data;
    }
    
    void MidiOutCore :: initialize( const std::string& clientName )
    {
      // Set up our client.
      MIDIClientRef client;
      OSStatus result = MIDIClientCreate( CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ), NULL, NULL, &client );
      if ( result != noErr ) {
        errorString_ = "MidiOutCore::initialize: error creating OS-X MIDI client object.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Save our api-specific connection information.
      CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
      data->client = client;
      data->endpoint = 0;
      apiData_ = (void *) data;
    }
    
    unsigned int MidiOutCore :: getPortCount()
    {
    
      CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
    
    SeeLook's avatar
    SeeLook committed
      return MIDIGetNumberOfDestinations();
    }
    
    std::string MidiOutCore :: getPortName( unsigned int portNumber )
    {
      CFStringRef nameRef;
      MIDIEndpointRef portRef;
      char name[128];
    
      std::string stringName;
    
      CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
    
    SeeLook's avatar
    SeeLook committed
      if ( portNumber >= MIDIGetNumberOfDestinations() ) {
    
    SeeLook's avatar
    SeeLook committed
        ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid.";
        errorString_ = ost.str();
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return stringName;
      }
    
      portRef = MIDIGetDestination( portNumber );
      nameRef = ConnectedEndpointName(portRef);
    
      CFStringGetCString( nameRef, name, sizeof(name), CFStringGetSystemEncoding());
    
    SeeLook's avatar
    SeeLook committed
      CFRelease( nameRef );
      
      return stringName = name;
    }
    
    void MidiOutCore :: openPort( unsigned int portNumber, const std::string portName )
    {
      if ( connected_ ) {
        errorString_ = "MidiOutCore::openPort: a valid connection already exists!";
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return;
      }
    
    
      CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
    
    SeeLook's avatar
    SeeLook committed
      unsigned int nDest = MIDIGetNumberOfDestinations();
      if (nDest < 1) {
        errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!";
    
        error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      if ( portNumber >= nDest ) {
    
    SeeLook's avatar
    SeeLook committed
        ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
        errorString_ = ost.str();
    
        error( RtMidiError::INVALID_PARAMETER, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      MIDIPortRef port;
      CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
      OSStatus result = MIDIOutputPortCreate( data->client, 
                                              CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
                                              &port );
      if ( result != noErr ) {
        MIDIClientDispose( data->client );
        errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Get the desired output port identifier.
      MIDIEndpointRef destination = MIDIGetDestination( portNumber );
      if ( destination == 0 ) {
        MIDIPortDispose( port );
        MIDIClientDispose( data->client );
        errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Save our api-specific connection information.
      data->port = port;
      data->destinationId = destination;
      connected_ = true;
    }
    
    void MidiOutCore :: closePort( void )
    {
      if ( connected_ ) {
        CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
        MIDIPortDispose( data->port );
        connected_ = false;
      }
    }
    
    void MidiOutCore :: openVirtualPort( std::string portName )
    {
      CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
    
      if ( data->endpoint ) {
        errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!";
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return;
      }
    
      // Create a virtual MIDI output source.
      MIDIEndpointRef endpoint;
      OSStatus result = MIDISourceCreate( data->client,
                                          CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ),
                                          &endpoint );
      if ( result != noErr ) {
        errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source.";
    
        error( RtMidiError::DRIVER_ERROR, errorString_ );
        return;
    
    SeeLook's avatar
    SeeLook committed
      }
    
      // Save our api-specific connection information.
      data->endpoint = endpoint;
    }
    
    
    // Not necessary if we don't treat sysex messages any differently than
    // normal messages ... see below.
    //static void sysexCompletionProc( MIDISysexSendRequest *sreq )
    //{
    //  free( sreq );
    //}
    
    SeeLook's avatar
    SeeLook committed
    
    void MidiOutCore :: sendMessage( std::vector<unsigned char> *message )
    {
      // We use the MIDISendSysex() function to asynchronously send sysex
      // messages.  Otherwise, we use a single CoreMidi MIDIPacket.
      unsigned int nBytes = message->size();
      if ( nBytes == 0 ) {
        errorString_ = "MidiOutCore::sendMessage: no data in message argument!";      
    
        error( RtMidiError::WARNING, errorString_ );
    
    SeeLook's avatar
    SeeLook committed
        return;