diff options
| author | Gary Scavone <gary@music.mcgill.ca> | 2013-10-11 14:49:11 +0200 |
|---|---|---|
| committer | Stephen Sinclair <sinclair@music.mcgill.ca> | 2013-10-11 14:49:11 +0200 |
| commit | 5f15183a557fc1d38da0eebd8bef1f860d394a66 (patch) | |
| tree | eac2cfa36ea6582680eb949a51345028df50467e /RtMidi.cpp | |
| parent | 1541e77944f030ef90dbebc6d94d6a4005f3200b (diff) | |
Version 2.0.0
Diffstat (limited to 'RtMidi.cpp')
| -rw-r--r-- | RtMidi.cpp | 2833 |
1 files changed, 1883 insertions, 950 deletions
@@ -8,7 +8,7 @@ RtMidi WWW site: http://music.mcgill.ca/~gary/rtmidi/ RtMidi: realtime MIDI i/o C++ classes - Copyright (c) 2003-2011 Gary P. Scavone + Copyright (c) 2003-2012 Gary P. Scavone Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files @@ -22,8 +22,9 @@ included in all copies or substantial portions of the Software. 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. + 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 @@ -35,61 +36,234 @@ */ /**********************************************************************/ -// RtMidi: Version 1.0.15 +// RtMidi: Version 2.0.0 #include "RtMidi.h" #include <sstream> //*********************************************************************// -// Common RtMidi Definitions +// RtMidi Definitions //*********************************************************************// -RtMidi :: RtMidi() - : apiData_( 0 ), connected_( false ) +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(__WINDOWS_KS__) + apis.push_back( WINDOWS_KS ); +#endif +#if defined(__RTMIDI_DUMMY__) + apis.push_back( RTMIDI_DUMMY ); +#endif } -void RtMidi :: error( RtError::Type type ) +void RtMidi :: error( RtError::Type type, std::string errorString ) { if (type == RtError::WARNING) { - std::cerr << '\n' << errorString_ << "\n\n"; + std::cerr << '\n' << errorString << "\n\n"; } else if (type == RtError::DEBUG_WARNING) { #if defined(__RTMIDI_DEBUG__) - std::cerr << '\n' << errorString_ << "\n\n"; + std::cerr << '\n' << errorString << "\n\n"; #endif } else { - std::cerr << '\n' << errorString_ << "\n\n"; - throw RtError( errorString_, type ); + std::cerr << '\n' << errorString << "\n\n"; + throw RtError( errorString, type ); } } //*********************************************************************// -// Common RtMidiIn Definitions +// RtMidiIn Definitions //*********************************************************************// -RtMidiIn :: RtMidiIn( const std::string clientName, unsigned int queueSizeLimit ) : RtMidi() +void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string clientName, unsigned int queueSizeLimit ) { - this->initialize( clientName ); + 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(__WINDOWS_KS__) + if ( api == WINDOWS_KS ) + rtapi_ = new MidiInWinKS( 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 ) +{ + rtapi_ = 0; + + 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 debug + // warning and continue as if no API was specified. + RtMidi::error( RtError::WARNING, "RtMidiIn: no compiled support for specified API argument!" ); + } + + // 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 print out an error message. + RtMidi::error( RtError::WARNING, "RtMidiIn: no compiled API support found ... critical error!!" ); +} + +RtMidiIn :: ~RtMidiIn() throw() +{ + delete rtapi_; +} + + +//*********************************************************************// +// 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(__WINDOWS_KS__) + if ( api == WINDOWS_KS ) + rtapi_ = new MidiOutWinKS( 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 ) +{ + rtapi_ = 0; + + if ( api != UNSPECIFIED ) { + // Attempt to open the specified API. + openMidiApi( api, clientName ); + if ( rtapi_ ) return; + + // No compiled support for specified API value. Issue a debug + // warning and continue as if no API was specified. + RtMidi::error( RtError::WARNING, "RtMidiOut: no compiled support for specified API argument!" ); + } + + // 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 print out an error message. + RtMidi::error( RtError::WARNING, "RtMidiOut: no compiled API support found ... critical error!!" ); +} + +RtMidiOut :: ~RtMidiOut() throw() +{ + delete rtapi_; +} + +//*********************************************************************// +// Common MidiInApi Definitions +//*********************************************************************// +MidiInApi :: MidiInApi( unsigned int queueSizeLimit ) + : apiData_( 0 ), connected_( false ) +{ // Allocate the MIDI queue. inputData_.queue.ringSize = queueSizeLimit; if ( inputData_.queue.ringSize > 0 ) inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ]; } -void RtMidiIn :: setCallback( RtMidiCallback callback, void *userData ) +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_ = "RtMidiIn::setCallback: a callback function is already set!"; - error( RtError::WARNING ); + errorString_ = "MidiInApi::setCallback: a callback function is already set!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } if ( !callback ) { errorString_ = "RtMidiIn::setCallback: callback function value is invalid!"; - error( RtError::WARNING ); + RtMidi::error( RtError::WARNING, errorString_ ); return; } @@ -98,11 +272,11 @@ void RtMidiIn :: setCallback( RtMidiCallback callback, void *userData ) inputData_.usingCallback = true; } -void RtMidiIn :: cancelCallback() +void MidiInApi :: cancelCallback() { if ( !inputData_.usingCallback ) { errorString_ = "RtMidiIn::cancelCallback: no callback function was set!"; - error( RtError::WARNING ); + RtMidi::error( RtError::WARNING, errorString_ ); return; } @@ -111,7 +285,7 @@ void RtMidiIn :: cancelCallback() inputData_.usingCallback = false; } -void RtMidiIn :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ) +void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ) { inputData_.ignoreFlags = 0; if ( midiSysex ) inputData_.ignoreFlags = 0x01; @@ -119,13 +293,13 @@ void RtMidiIn :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ) if ( midiSense ) inputData_.ignoreFlags |= 0x04; } -double RtMidiIn :: getMessage( std::vector<unsigned char> *message ) +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( RtError::WARNING ); + RtMidi::error( RtError::WARNING, errorString_ ); return 0.0; } @@ -144,21 +318,23 @@ double RtMidiIn :: getMessage( std::vector<unsigned char> *message ) } //*********************************************************************// -// Common RtMidiOut Definitions +// Common MidiOutApi Definitions //*********************************************************************// -RtMidiOut :: RtMidiOut( const std::string clientName ) : RtMidi() +MidiOutApi :: MidiOutApi( void ) + : apiData_( 0 ), connected_( false ) { - this->initialize( clientName ); } +MidiOutApi :: ~MidiOutApi( void ) +{ +} -//*********************************************************************// -// API: Macintosh OS-X -//*********************************************************************// - -// API information found at: -// - http://developer.apple.com/audio/pdf/coreaudio.pdf +// *************************************************** // +// +// OS/API-specific methods. +// +// *************************************************** // #if defined(__MACOSX_CORE__) @@ -184,12 +360,12 @@ struct CoreMidiData { //*********************************************************************// // API: OS-X -// Class Definitions: RtMidiIn +// Class Definitions: MidiInCore //*********************************************************************// void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef ) { - RtMidiIn::RtMidiInData *data = static_cast<RtMidiIn::RtMidiInData *> (procRef); + MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef); CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData); unsigned char status; @@ -197,7 +373,7 @@ void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef unsigned long long time; bool& continueSysex = data->continueSysex; - RtMidiIn::MidiMessage& message = data->message; + MidiInApi::MidiMessage& message = data->message; const MIDIPacket *packet = &list->packet[0]; for ( unsigned int i=0; i<list->numPackets; ++i ) { @@ -215,9 +391,11 @@ void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef if ( nBytes == 0 ) continue; // Calculate time stamp. - message.timeStamp = 0.0; - if ( data->firstMessage ) + + if ( data->firstMessage ) { + message.timeStamp = 0.0; data->firstMessage = false; + } else { time = packet->timeStamp; if ( time == 0 ) { // this happens when receiving asynchronous sysex messages @@ -225,7 +403,8 @@ void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef } time -= apiData->lastTime; time = AudioConvertHostTimeToNanos( time ); - message.timeStamp = time * 0.000000001; + if ( !continueSysex ) + message.timeStamp = time * 0.000000001; } apiData->lastTime = packet->timeStamp; if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages @@ -245,7 +424,7 @@ void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef if ( !continueSysex ) { // If not a continuing sysex message, invoke the user callback function or queue the message. - if ( data->usingCallback && message.bytes.size() > 0 ) { + if ( data->usingCallback ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( message.timeStamp, &message.bytes, data->userData ); } @@ -258,7 +437,7 @@ void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef data->queue.size++; } else - std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; + std::cerr << "\nMidiInCore: message queue limit reached!!\n\n"; } message.bytes.clear(); } @@ -322,7 +501,7 @@ void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef data->queue.size++; } else - std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; + std::cerr << "\nMidiInCore: message queue limit reached!!\n\n"; } message.bytes.clear(); } @@ -334,14 +513,31 @@ void midiInputCallback( const MIDIPacketList *list, void *procRef, void *srcRef } } -void RtMidiIn :: initialize( const std::string& clientName ) +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_ = "RtMidiIn::initialize: error creating OS-X MIDI client object."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInCore::initialize: error creating OS-X MIDI client object."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Save our api-specific connection information. @@ -352,25 +548,25 @@ void RtMidiIn :: initialize( const std::string& clientName ) inputData_.apiData = (void *) data; } -void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) +void MidiInCore :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { - errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; - error( RtError::WARNING ); + errorString_ = "MidiInCore::openPort: a valid connection already exists!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } unsigned int nSrc = MIDIGetNumberOfSources(); if (nSrc < 1) { - errorString_ = "RtMidiIn::openPort: no MIDI input sources found!"; - error( RtError::NO_DEVICES_FOUND ); + errorString_ = "MidiInCore::openPort: no MIDI input sources found!"; + RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ ); } std::ostringstream ost; if ( portNumber >= nSrc ) { - ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); + RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); } MIDIPortRef port; @@ -380,8 +576,8 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) midiInputCallback, (void *)&inputData_, &port ); if ( result != noErr ) { MIDIClientDispose( data->client ); - errorString_ = "RtMidiIn::openPort: error creating OS-X MIDI input port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Get the desired input source identifier. @@ -389,8 +585,8 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) if ( endpoint == 0 ) { MIDIPortDispose( port ); MIDIClientDispose( data->client ); - errorString_ = "RtMidiIn::openPort: error getting MIDI input source reference."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInCore::openPort: error getting MIDI input source reference."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Make the connection. @@ -398,8 +594,8 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) if ( result != noErr ) { MIDIPortDispose( port ); MIDIClientDispose( data->client ); - errorString_ = "RtMidiIn::openPort: error connecting OS-X MIDI input port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Save our api-specific port information. @@ -408,7 +604,7 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) connected_ = true; } -void RtMidiIn :: openVirtualPort( const std::string portName ) +void MidiInCore :: openVirtualPort( const std::string portName ) { CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); @@ -418,15 +614,15 @@ void RtMidiIn :: openVirtualPort( const std::string portName ) CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ), midiInputCallback, (void *)&inputData_, &endpoint ); if ( result != noErr ) { - errorString_ = "RtMidiIn::openVirtualPort: error creating virtual OS-X MIDI destination."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Save our api-specific connection information. data->endpoint = endpoint; } -void RtMidiIn :: closePort( void ) +void MidiInCore :: closePort( void ) { if ( connected_ ) { CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); @@ -435,22 +631,7 @@ void RtMidiIn :: closePort( void ) } } -RtMidiIn :: ~RtMidiIn() -{ - // 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; - - // Delete the MIDI queue. - if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring; -} - -unsigned int RtMidiIn :: getPortCount() +unsigned int MidiInCore :: getPortCount() { return MIDIGetNumberOfSources(); } @@ -579,7 +760,7 @@ static CFStringRef ConnectedEndpointName( MIDIEndpointRef endpoint ) return EndpointName( endpoint, false ); } -std::string RtMidiIn :: getPortName( unsigned int portNumber ) +std::string MidiInCore :: getPortName( unsigned int portNumber ) { CFStringRef nameRef; MIDIEndpointRef portRef; @@ -588,10 +769,10 @@ std::string RtMidiIn :: getPortName( unsigned int portNumber ) std::string stringName; if ( portNumber >= MIDIGetNumberOfSources() ) { - ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::WARNING ); - //error( RtError::INVALID_PARAMETER ); + RtMidi::error( RtError::WARNING, errorString_ ); + //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); return stringName; } @@ -605,15 +786,49 @@ std::string RtMidiIn :: getPortName( unsigned int portNumber ) //*********************************************************************// // API: OS-X -// Class Definitions: RtMidiOut +// Class Definitions: MidiOutCore //*********************************************************************// -unsigned int RtMidiOut :: getPortCount() +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."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); + } + + // Save our api-specific connection information. + CoreMidiData *data = (CoreMidiData *) new CoreMidiData; + data->client = client; + data->endpoint = 0; + apiData_ = (void *) data; +} + +unsigned int MidiOutCore :: getPortCount() { return MIDIGetNumberOfDestinations(); } -std::string RtMidiOut :: getPortName( unsigned int portNumber ) +std::string MidiOutCore :: getPortName( unsigned int portNumber ) { CFStringRef nameRef; MIDIEndpointRef portRef; @@ -622,11 +837,11 @@ std::string RtMidiOut :: getPortName( unsigned int portNumber ) std::string stringName; if ( portNumber >= MIDIGetNumberOfDestinations() ) { - ost << "RtMidiOut::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::WARNING ); + RtMidi::error( RtError::WARNING, errorString_ ); return stringName; - //error( RtError::INVALID_PARAMETER ); + //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); } portRef = MIDIGetDestination( portNumber ); @@ -637,42 +852,25 @@ std::string RtMidiOut :: getPortName( unsigned int portNumber ) return stringName = name; } -void RtMidiOut :: 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_ = "RtMidiOut::initialize: error creating OS-X MIDI client object."; - error( RtError::DRIVER_ERROR ); - } - - // Save our api-specific connection information. - CoreMidiData *data = (CoreMidiData *) new CoreMidiData; - data->client = client; - data->endpoint = 0; - apiData_ = (void *) data; -} - -void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName ) +void MidiOutCore :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { - errorString_ = "RtMidiOut::openPort: a valid connection already exists!"; - error( RtError::WARNING ); + errorString_ = "MidiOutCore::openPort: a valid connection already exists!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } unsigned int nDest = MIDIGetNumberOfDestinations(); if (nDest < 1) { - errorString_ = "RtMidiOut::openPort: no MIDI output destinations found!"; - error( RtError::NO_DEVICES_FOUND ); + errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!"; + RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ ); } std::ostringstream ost; if ( portNumber >= nDest ) { - ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); + RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); } MIDIPortRef port; @@ -682,8 +880,8 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName &port ); if ( result != noErr ) { MIDIClientDispose( data->client ); - errorString_ = "RtMidiOut::openPort: error creating OS-X MIDI output port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Get the desired output port identifier. @@ -691,8 +889,8 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName if ( destination == 0 ) { MIDIPortDispose( port ); MIDIClientDispose( data->client ); - errorString_ = "RtMidiOut::openPort: error getting MIDI output destination reference."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Save our api-specific connection information. @@ -701,7 +899,7 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName connected_ = true; } -void RtMidiOut :: closePort( void ) +void MidiOutCore :: closePort( void ) { if ( connected_ ) { CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); @@ -710,13 +908,13 @@ void RtMidiOut :: closePort( void ) } } -void RtMidiOut :: openVirtualPort( std::string portName ) +void MidiOutCore :: openVirtualPort( std::string portName ) { CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); if ( data->endpoint ) { - errorString_ = "RtMidiOut::openVirtualPort: a virtual output port already exists!"; - error( RtError::WARNING ); + errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } @@ -726,26 +924,14 @@ void RtMidiOut :: openVirtualPort( std::string portName ) CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ), &endpoint ); if ( result != noErr ) { - errorString_ = "RtMidiOut::initialize: error creating OS-X virtual MIDI source."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Save our api-specific connection information. data->endpoint = endpoint; } -RtMidiOut :: ~RtMidiOut() -{ - // 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; -} - char *sysexBuffer = 0; void sysexCompletionProc( MIDISysexSendRequest * sreq ) @@ -755,14 +941,14 @@ void sysexCompletionProc( MIDISysexSendRequest * sreq ) sysexBuffer = 0; } -void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) +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_ = "RtMidiOut::sendMessage: no data in message argument!"; - error( RtError::WARNING ); + errorString_ = "MidiOutCore::sendMessage: no data in message argument!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } @@ -778,8 +964,8 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) sysexBuffer = new char[nBytes]; if ( sysexBuffer == NULL ) { - errorString_ = "RtMidiOut::sendMessage: error allocating sysex message memory!"; - error( RtError::MEMORY_ERROR ); + errorString_ = "MidiOutCore::sendMessage: error allocating sysex message memory!"; + RtMidi::error( RtError::MEMORY_ERROR, errorString_ ); } // Copy data to buffer. @@ -794,14 +980,14 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) result = MIDISendSysex( &(data->sysexreq) ); if ( result != noErr ) { - errorString_ = "RtMidiOut::sendMessage: error sending MIDI to virtual destinations."; - error( RtError::WARNING ); + errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations."; + RtMidi::error( RtError::WARNING, errorString_ ); } return; } else if ( nBytes > 3 ) { - errorString_ = "RtMidiOut::sendMessage: message format problem ... not sysex but > 3 bytes?"; - error( RtError::WARNING ); + errorString_ = "MidiOutCore::sendMessage: message format problem ... not sysex but > 3 bytes?"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } @@ -809,16 +995,16 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) MIDIPacket *packet = MIDIPacketListInit( &packetList ); packet = MIDIPacketListAdd( &packetList, sizeof(packetList), packet, timeStamp, nBytes, (const Byte *) &message->at( 0 ) ); if ( !packet ) { - errorString_ = "RtMidiOut::sendMessage: could not allocate packet list"; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutCore::sendMessage: could not allocate packet list"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Send to any destinations that may have connected to us. if ( data->endpoint ) { result = MIDIReceived( data->endpoint, &packetList ); if ( result != noErr ) { - errorString_ = "RtMidiOut::sendMessage: error sending MIDI to virtual destinations."; - error( RtError::WARNING ); + errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations."; + RtMidi::error( RtError::WARNING, errorString_ ); } } @@ -826,8 +1012,8 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) if ( connected_ ) { result = MIDISend( data->port, data->destinationId, &packetList ); if ( result != noErr ) { - errorString_ = "RtMidiOut::sendMessage: error sending MIDI message to port."; - error( RtError::WARNING ); + errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port."; + RtMidi::error( RtError::WARNING, errorString_ ); } } @@ -843,7 +1029,7 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) // API information found at: // - http://www.alsa-project.org/documentation.php#Library -#if defined(__LINUX_ALSASEQ__) +#if defined(__LINUX_ALSA__) // The ALSA Sequencer API is based on the use of a callback function for // MIDI input. @@ -861,37 +1047,85 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) // ALSA header file. #include <alsa/asoundlib.h> +// Global sequencer instance created when first In/Out object is +// created, then destroyed when last In/Out is deleted. +static snd_seq_t *s_seq = NULL; + +// Variable to keep track of how many ports are open. +static unsigned int s_numPorts = 0; + +// The client name to use when creating the sequencer, which is +// currently set on the first call to createSequencer. +static string s_clientName = "RtMidi Client"; + // A structure to hold variables related to the ALSA API // implementation. struct AlsaMidiData { snd_seq_t *seq; + unsigned int portNum; int vport; snd_seq_port_subscribe_t *subscription; snd_midi_event_t *coder; unsigned int bufferSize; unsigned char *buffer; pthread_t thread; + pthread_t dummy_thread_id; unsigned long long lastTime; int queue_id; // an input queue is needed to get timestamped events + int trigger_fds[2]; }; #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits)) +snd_seq_t* createSequencer( const std::string& clientName ) +{ + // Set up the ALSA sequencer client. + if ( s_seq == NULL ) { + int result = snd_seq_open(&s_seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK); + if ( result < 0 ) { + s_seq = NULL; + } + else { + // Set client name, use current name if given string is empty. + if ( clientName != "" ) { + s_clientName = clientName; + } + snd_seq_set_client_name( s_seq, s_clientName.c_str() ); + } + } + + // Increment port count. + s_numPorts++; + + return s_seq; +} + +void freeSequencer ( void ) +{ + s_numPorts--; + if ( s_numPorts == 0 && s_seq != NULL ) { + snd_seq_close( s_seq ); + s_seq = NULL; + } +} + //*********************************************************************// // API: LINUX ALSA -// Class Definitions: RtMidiIn +// Class Definitions: MidiInAlsa //*********************************************************************// extern "C" void *alsaMidiHandler( void *ptr ) { - RtMidiIn::RtMidiInData *data = static_cast<RtMidiIn::RtMidiInData *> (ptr); + MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (ptr); AlsaMidiData *apiData = static_cast<AlsaMidiData *> (data->apiData); long nBytes; unsigned long long time, lastTime; bool continueSysex = false; bool doDecode = false; - RtMidiIn::MidiMessage message; + MidiInApi::MidiMessage message; + int poll_fd_count; + struct pollfd *poll_fds; snd_seq_event_t *ev; int result; @@ -899,34 +1133,48 @@ extern "C" void *alsaMidiHandler( void *ptr ) result = snd_midi_event_new( 0, &apiData->coder ); if ( result < 0 ) { data->doInput = false; - std::cerr << "\nRtMidiIn::alsaMidiHandler: error initializing MIDI event parser!\n\n"; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n"; return 0; } unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize ); if ( buffer == NULL ) { data->doInput = false; - std::cerr << "\nRtMidiIn::alsaMidiHandler: error initializing buffer memory!\n\n"; + snd_midi_event_free( apiData->coder ); + apiData->coder = 0; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n"; return 0; } snd_midi_event_init( apiData->coder ); snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages + poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1; + poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd )); + snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN ); + poll_fds[0].fd = apiData->trigger_fds[0]; + poll_fds[0].events = POLLIN; + while ( data->doInput ) { if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) { - // No data pending ... sleep a bit. - usleep( 1000 ); + // No data pending + if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) { + if ( poll_fds[0].revents & POLLIN ) { + bool dummy; + int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) ); + (void) res; + } + } continue; } // If here, there should be data. result = snd_seq_event_input( apiData->seq, &ev ); if ( result == -ENOSPC ) { - std::cerr << "\nRtMidiIn::alsaMidiHandler: MIDI input buffer overrun!\n\n"; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n"; continue; } else if ( result <= 0 ) { - std::cerr << "RtMidiIn::alsaMidiHandler: unknown MIDI input error!\n"; + std::cerr << "MidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n"; continue; } @@ -939,13 +1187,13 @@ extern "C" void *alsaMidiHandler( void *ptr ) case SND_SEQ_EVENT_PORT_SUBSCRIBED: #if defined(__RTMIDI_DEBUG__) - std::cout << "RtMidiIn::alsaMidiHandler: port connection made!\n"; + std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n"; #endif break; case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: #if defined(__RTMIDI_DEBUG__) - std::cerr << "RtMidiIn::alsaMidiHandler: port connection has closed!\n"; + std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n"; std::cout << "sender = " << (int) ev->data.connect.sender.client << ":" << (int) ev->data.connect.sender.port << ", dest = " << (int) ev->data.connect.dest.client << ":" @@ -974,7 +1222,7 @@ extern "C" void *alsaMidiHandler( void *ptr ) buffer = (unsigned char *) malloc( apiData->bufferSize ); if ( buffer == NULL ) { data->doInput = false; - std::cerr << "\nRtMidiIn::alsaMidiHandler: error resizing buffer memory!\n\n"; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n"; break; } } @@ -1020,16 +1268,16 @@ extern "C" void *alsaMidiHandler( void *ptr ) } else { #if defined(__RTMIDI_DEBUG__) - std::cerr << "\nRtMidiIn::alsaMidiHandler: event parsing error or not a MIDI event!\n\n"; + std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n"; #endif } } } snd_seq_free_event( ev ); - if ( message.bytes.size() == 0 ) continue; + if ( message.bytes.size() == 0 || continueSysex ) continue; - if ( data->usingCallback && !continueSysex ) { + if ( data->usingCallback ) { RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; callback( message.timeStamp, &message.bytes, data->userData ); } @@ -1042,39 +1290,78 @@ extern "C" void *alsaMidiHandler( void *ptr ) data->queue.size++; } else - std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; + std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n"; } } if ( buffer ) free( buffer ); snd_midi_event_free( apiData->coder ); apiData->coder = 0; + apiData->thread = apiData->dummy_thread_id; return 0; } -void RtMidiIn :: initialize( const std::string& clientName ) +MidiInAlsa :: MidiInAlsa( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit ) { - // Set up the ALSA sequencer client. - snd_seq_t *seq; - int result = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK); - if ( result < 0 ) { - errorString_ = "RtMidiIn::initialize: error creating ALSA sequencer input client object."; - error( RtError::DRIVER_ERROR ); - } + initialize( clientName ); +} + +MidiInAlsa :: ~MidiInAlsa() +{ + // Close a connection if it exists. + closePort(); + + // Shutdown the input thread. + AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); + if ( inputData_.doInput ) { + inputData_.doInput = false; + int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) ); + (void) res; + if ( !pthread_equal(data->thread, data->dummy_thread_id) ) + pthread_join( data->thread, NULL ); + } + + // Cleanup. + close ( data->trigger_fds[0] ); + close ( data->trigger_fds[1] ); + if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); +#ifndef AVOID_TIMESTAMPING + snd_seq_free_queue( data->seq, data->queue_id ); +#endif + freeSequencer(); + delete data; +} - // Set client name. - snd_seq_set_client_name( seq, clientName.c_str() ); +void MidiInAlsa :: initialize( const std::string& clientName ) +{ + snd_seq_t* seq = createSequencer( clientName ); + if ( seq == NULL ) { + s_seq = NULL; + errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); + } // Save our api-specific connection information. AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; data->seq = seq; + data->portNum = -1; data->vport = -1; + data->subscription = 0; + data->dummy_thread_id = pthread_self(); + data->thread = data->dummy_thread_id; + data->trigger_fds[0] = -1; + data->trigger_fds[1] = -1; apiData_ = (void *) data; inputData_.apiData = (void *) data; + if ( pipe(data->trigger_fds) == -1 ) { + errorString_ = "MidiInAlsa::initialize: error creating pipe objects."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); + } + // Create the input queue #ifndef AVOID_TIMESTAMPING - data->queue_id = snd_seq_alloc_named_queue(seq, "RtMidi Queue"); + data->queue_id = snd_seq_alloc_named_queue(s_seq, "RtMidi Queue"); // Set arbitrary tempo (mm=100) and resolution (240) snd_seq_queue_tempo_t *qtempo; snd_seq_queue_tempo_alloca(&qtempo); @@ -1088,55 +1375,93 @@ void RtMidiIn :: initialize( const std::string& clientName ) // This function is used to count or get the pinfo structure for a given port number. unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber ) { - snd_seq_client_info_t *cinfo; + snd_seq_client_info_t *cinfo; int client; int count = 0; - snd_seq_client_info_alloca( &cinfo ); + snd_seq_client_info_alloca( &cinfo ); - snd_seq_client_info_set_client( cinfo, -1 ); - while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) { + snd_seq_client_info_set_client( cinfo, -1 ); + while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) { client = snd_seq_client_info_get_client( cinfo ); if ( client == 0 ) continue; - // Reset query info - snd_seq_port_info_set_client( pinfo, client ); - snd_seq_port_info_set_port( pinfo, -1 ); - while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) { + // Reset query info + snd_seq_port_info_set_client( pinfo, client ); + snd_seq_port_info_set_port( pinfo, -1 ); + while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) { unsigned int atyp = snd_seq_port_info_get_type( pinfo ); if ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) continue; unsigned int caps = snd_seq_port_info_get_capability( pinfo ); if ( ( caps & type ) != type ) continue; if ( count == portNumber ) return 1; ++count; - } - } + } + } // If a negative portNumber was used, return the port count. if ( portNumber < 0 ) return count; return 0; } -void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) +unsigned int MidiInAlsa :: getPortCount() +{ + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); + + AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); + return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 ); +} + +std::string MidiInAlsa :: getPortName( unsigned int portNumber ) +{ + snd_seq_client_info_t *cinfo; + snd_seq_port_info_t *pinfo; + snd_seq_client_info_alloca( &cinfo ); + snd_seq_port_info_alloca( &pinfo ); + + std::string stringName; + AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); + if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) { + int cnum = snd_seq_port_info_get_client( pinfo ); + snd_seq_get_any_client_info( data->seq, cnum, cinfo ); + std::ostringstream os; + os << snd_seq_client_info_get_name( cinfo ); + os << " "; // GO: These lines added to make sure devices are listed + os << snd_seq_port_info_get_client( pinfo ); // GO: with full portnames added to ensure individual device names + os << ":"; + os << snd_seq_port_info_get_port( pinfo ); + stringName = os.str(); + return stringName; + } + + // If we get here, we didn't find a match. + errorString_ = "MidiInAlsa::getPortName: error looking for port name!"; + RtMidi::error( RtError::WARNING, errorString_ ); + return stringName; + //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); +} + +void MidiInAlsa :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { - errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; - error( RtError::WARNING ); + errorString_ = "MidiInAlsa::openPort: a valid connection already exists!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } unsigned int nSrc = this->getPortCount(); if (nSrc < 1) { - errorString_ = "RtMidiIn::openPort: no MIDI input sources found!"; - error( RtError::NO_DEVICES_FOUND ); + errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!"; + RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ ); } - snd_seq_port_info_t *pinfo; - snd_seq_port_info_alloca( &pinfo ); + snd_seq_port_info_t *pinfo; + snd_seq_port_info_alloca( &pinfo ); std::ostringstream ost; AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) { - ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); + RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); } @@ -1163,20 +1488,27 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) data->vport = snd_seq_create_port(data->seq, pinfo); if ( data->vport < 0 ) { - errorString_ = "RtMidiIn::openPort: ALSA error creating input port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInAlsa::openPort: ALSA error creating input port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } receiver.port = data->vport; - // Make subscription - snd_seq_port_subscribe_malloc( &data->subscription ); - snd_seq_port_subscribe_set_sender(data->subscription, &sender); - snd_seq_port_subscribe_set_dest(data->subscription, &receiver); - if ( snd_seq_subscribe_port(data->seq, data->subscription) ) { - errorString_ = "RtMidiIn::openPort: ALSA error making port connection."; - error( RtError::DRIVER_ERROR ); + if ( !data->subscription ) { + // Make subscription + if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) { + errorString_ = "MidiInAlsa::openPort: ALSA error allocation port subscription."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); + } + snd_seq_port_subscribe_set_sender(data->subscription, &sender); + snd_seq_port_subscribe_set_dest(data->subscription, &receiver); + if ( snd_seq_subscribe_port(data->seq, data->subscription) ) { + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + errorString_ = "MidiInAlsa::openPort: ALSA error making port connection."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); + } } if ( inputData_.doInput == false ) { @@ -1194,19 +1526,20 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) inputData_.doInput = true; int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_); pthread_attr_destroy(&attr); - if (err) { + if ( err ) { snd_seq_unsubscribe_port( data->seq, data->subscription ); snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; inputData_.doInput = false; - errorString_ = "RtMidiIn::openPort: error starting MIDI input thread!"; - error( RtError::THREAD_ERROR ); + errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!"; + RtMidi::error( RtError::THREAD_ERROR, errorString_ ); } } connected_ = true; } -void RtMidiIn :: openVirtualPort( std::string portName ) +void MidiInAlsa :: openVirtualPort( std::string portName ) { AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); if ( data->vport < 0 ) { @@ -1228,12 +1561,16 @@ void RtMidiIn :: openVirtualPort( std::string portName ) data->vport = snd_seq_create_port(data->seq, pinfo); if ( data->vport < 0 ) { - errorString_ = "RtMidiIn::openVirtualPort: ALSA error creating virtual port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInAlsa::openVirtualPort: ALSA error creating virtual port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } if ( inputData_.doInput == false ) { + // Wait for old thread to stop, if still running + if ( !pthread_equal(data->thread, data->dummy_thread_id) ) + pthread_join( data->thread, NULL ); + // Start the input queue #ifndef AVOID_TIMESTAMPING snd_seq_start_queue( data->seq, data->queue_id, NULL ); @@ -1248,22 +1585,29 @@ void RtMidiIn :: openVirtualPort( std::string portName ) inputData_.doInput = true; int err = pthread_create(&data->thread, &attr, alsaMidiHandler, &inputData_); pthread_attr_destroy(&attr); - if (err) { - snd_seq_unsubscribe_port( data->seq, data->subscription ); - snd_seq_port_subscribe_free( data->subscription ); + if ( err ) { + if ( data->subscription ) { + snd_seq_unsubscribe_port( data->seq, data->subscription ); + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + } inputData_.doInput = false; - errorString_ = "RtMidiIn::openPort: error starting MIDI input thread!"; - error( RtError::THREAD_ERROR ); + errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!"; + RtMidi::error( RtError::THREAD_ERROR, errorString_ ); } } } -void RtMidiIn :: closePort( void ) +void MidiInAlsa :: closePort( void ) { + AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); + if ( connected_ ) { - AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); - snd_seq_unsubscribe_port( data->seq, data->subscription ); - snd_seq_port_subscribe_free( data->subscription ); + if ( data->subscription ) { + snd_seq_unsubscribe_port( data->seq, data->subscription ); + snd_seq_port_subscribe_free( data->subscription ); + data->subscription = 0; + } // Stop the input queue #ifndef AVOID_TIMESTAMPING snd_seq_stop_queue( data->seq, data->queue_id, NULL ); @@ -1271,74 +1615,75 @@ void RtMidiIn :: closePort( void ) #endif connected_ = false; } -} -RtMidiIn :: ~RtMidiIn() -{ - // Close a connection if it exists. - closePort(); - - // Shutdown the input thread. - AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); + // Stop thread to avoid triggering the callback, while the port is intended to be closed if ( inputData_.doInput ) { inputData_.doInput = false; - pthread_join( data->thread, NULL ); + int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof(inputData_.doInput) ); + (void) res; + if ( !pthread_equal(data->thread, data->dummy_thread_id) ) + pthread_join( data->thread, NULL ); } +} - // Cleanup. - if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); -#ifndef AVOID_TIMESTAMPING - snd_seq_free_queue( data->seq, data->queue_id ); -#endif - snd_seq_close( data->seq ); - delete data; +//*********************************************************************// +// API: LINUX ALSA +// Class Definitions: MidiOutAlsa +//*********************************************************************// - // Delete the MIDI queue. - if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring; +MidiOutAlsa :: MidiOutAlsa( const std::string clientName ) : MidiOutApi() +{ + initialize( clientName ); } -unsigned int RtMidiIn :: getPortCount() +MidiOutAlsa :: ~MidiOutAlsa() { - snd_seq_port_info_t *pinfo; - snd_seq_port_info_alloca( &pinfo ); + // Close a connection if it exists. + closePort(); + // Cleanup. AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); - return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 ); + if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); + if ( data->coder ) snd_midi_event_free( data->coder ); + if ( data->buffer ) free( data->buffer ); + freeSequencer(); + delete data; } -std::string RtMidiIn :: getPortName( unsigned int portNumber ) +void MidiOutAlsa :: initialize( const std::string& clientName ) { - snd_seq_client_info_t *cinfo; - snd_seq_port_info_t *pinfo; - snd_seq_client_info_alloca( &cinfo ); - snd_seq_port_info_alloca( &pinfo ); + snd_seq_t* seq = createSequencer( clientName ); + if ( seq == NULL ) { + s_seq = NULL; + errorString_ = "MidiOutAlsa::initialize: error creating ALSA sequencer client object."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); + } - std::string stringName; - AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); - if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) { - int cnum = snd_seq_port_info_get_client( pinfo ); - snd_seq_get_any_client_info( data->seq, cnum, cinfo ); - std::ostringstream os; - os << snd_seq_client_info_get_name( cinfo ); - os << ":"; - os << snd_seq_port_info_get_port( pinfo ); - stringName = os.str(); - return stringName; + // Save our api-specific connection information. + AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; + data->seq = seq; + data->portNum = -1; + data->vport = -1; + data->bufferSize = 32; + data->coder = 0; + data->buffer = 0; + int result = snd_midi_event_new( data->bufferSize, &data->coder ); + if ( result < 0 ) { + delete data; + errorString_ = "MidiOutAlsa::initialize: error initializing MIDI event parser!\n\n"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } - - // If we get here, we didn't find a match. - errorString_ = "RtMidiIn::getPortName: error looking for port name!"; - error( RtError::WARNING ); - return stringName; - //error( RtError::INVALID_PARAMETER ); + data->buffer = (unsigned char *) malloc( data->bufferSize ); + if ( data->buffer == NULL ) { + delete data; + errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n"; + RtMidi::error( RtError::MEMORY_ERROR, errorString_ ); + } + snd_midi_event_init( data->coder ); + apiData_ = (void *) data; } -//*********************************************************************// -// API: LINUX ALSA -// Class Definitions: RtMidiOut -//*********************************************************************// - -unsigned int RtMidiOut :: getPortCount() +unsigned int MidiOutAlsa :: getPortCount() { snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca( &pinfo ); @@ -1347,7 +1692,7 @@ unsigned int RtMidiOut :: getPortCount() return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 ); } -std::string RtMidiOut :: getPortName( unsigned int portNumber ) +std::string MidiOutAlsa :: getPortName( unsigned int portNumber ) { snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; @@ -1368,60 +1713,24 @@ std::string RtMidiOut :: getPortName( unsigned int portNumber ) } // If we get here, we didn't find a match. - errorString_ = "RtMidiOut::getPortName: error looking for port name!"; - //error( RtError::INVALID_PARAMETER ); - error( RtError::WARNING ); + errorString_ = "MidiOutAlsa::getPortName: error looking for port name!"; + //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); + RtMidi::error( RtError::WARNING, errorString_ ); return stringName; } -void RtMidiOut :: initialize( const std::string& clientName ) -{ - // Set up the ALSA sequencer client. - snd_seq_t *seq; - int result = snd_seq_open( &seq, "default", SND_SEQ_OPEN_OUTPUT, SND_SEQ_NONBLOCK ); - if ( result < 0 ) { - errorString_ = "RtMidiOut::initialize: error creating ALSA sequencer client object."; - error( RtError::DRIVER_ERROR ); - } - - // Set client name. - snd_seq_set_client_name( seq, clientName.c_str() ); - - // Save our api-specific connection information. - AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; - data->seq = seq; - data->vport = -1; - data->bufferSize = 32; - data->coder = 0; - data->buffer = 0; - result = snd_midi_event_new( data->bufferSize, &data->coder ); - if ( result < 0 ) { - delete data; - errorString_ = "RtMidiOut::initialize: error initializing MIDI event parser!\n\n"; - error( RtError::DRIVER_ERROR ); - } - data->buffer = (unsigned char *) malloc( data->bufferSize ); - if ( data->buffer == NULL ) { - delete data; - errorString_ = "RtMidiOut::initialize: error allocating buffer memory!\n\n"; - error( RtError::MEMORY_ERROR ); - } - snd_midi_event_init( data->coder ); - apiData_ = (void *) data; -} - -void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName ) +void MidiOutAlsa :: openPort( unsigned int portNumber, const std::string portName ) { if ( connected_ ) { - errorString_ = "RtMidiOut::openPort: a valid connection already exists!"; - error( RtError::WARNING ); + errorString_ = "MidiOutAlsa::openPort: a valid connection already exists!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } unsigned int nSrc = this->getPortCount(); if (nSrc < 1) { - errorString_ = "RtMidiOut::openPort: no MIDI output sources found!"; - error( RtError::NO_DEVICES_FOUND ); + errorString_ = "MidiOutAlsa::openPort: no MIDI output sources found!"; + RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ ); } snd_seq_port_info_t *pinfo; @@ -1429,9 +1738,9 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName std::ostringstream ost; AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) { - ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiOutAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); + RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); } snd_seq_addr_t sender, receiver; @@ -1444,28 +1753,33 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION ); if ( data->vport < 0 ) { - errorString_ = "RtMidiOut::openPort: ALSA error creating output port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutAlsa::openPort: ALSA error creating output port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } sender.port = data->vport; // Make subscription - snd_seq_port_subscribe_malloc( &data->subscription ); + if (snd_seq_port_subscribe_malloc( &data->subscription ) < 0) { + snd_seq_port_subscribe_free( data->subscription ); + errorString_ = "MidiOutAlsa::openPort: error allocation port subscribtion."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); + } snd_seq_port_subscribe_set_sender(data->subscription, &sender); snd_seq_port_subscribe_set_dest(data->subscription, &receiver); snd_seq_port_subscribe_set_time_update(data->subscription, 1); snd_seq_port_subscribe_set_time_real(data->subscription, 1); if ( snd_seq_subscribe_port(data->seq, data->subscription) ) { - errorString_ = "RtMidiOut::openPort: ALSA error making port connection."; - error( RtError::DRIVER_ERROR ); + snd_seq_port_subscribe_free( data->subscription ); + errorString_ = "MidiOutAlsa::openPort: ALSA error making port connection."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } connected_ = true; } -void RtMidiOut :: closePort( void ) +void MidiOutAlsa :: closePort( void ) { if ( connected_ ) { AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); @@ -1475,7 +1789,7 @@ void RtMidiOut :: closePort( void ) } } -void RtMidiOut :: openVirtualPort( std::string portName ) +void MidiOutAlsa :: openVirtualPort( std::string portName ) { AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); if ( data->vport < 0 ) { @@ -1484,27 +1798,13 @@ void RtMidiOut :: openVirtualPort( std::string portName ) SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION ); if ( data->vport < 0 ) { - errorString_ = "RtMidiOut::openVirtualPort: ALSA error creating virtual port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutAlsa::openVirtualPort: ALSA error creating virtual port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } } -RtMidiOut :: ~RtMidiOut() -{ - // Close a connection if it exists. - closePort(); - - // Cleanup. - AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); - if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); - if ( data->coder ) snd_midi_event_free( data->coder ); - if ( data->buffer ) free( data->buffer ); - snd_seq_close( data->seq ); - delete data; -} - -void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) +void MidiOutAlsa :: sendMessage( std::vector<unsigned char> *message ) { int result; AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); @@ -1513,14 +1813,14 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) data->bufferSize = nBytes; result = snd_midi_event_resize_buffer ( data->coder, nBytes); if ( result != 0 ) { - errorString_ = "RtMidiOut::sendMessage: ALSA error resizing MIDI event buffer."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutAlsa::sendMessage: ALSA error resizing MIDI event buffer."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } free (data->buffer); data->buffer = (unsigned char *) malloc( data->bufferSize ); if ( data->buffer == NULL ) { - errorString_ = "RtMidiOut::initialize: error allocating buffer memory!\n\n"; - error( RtError::MEMORY_ERROR ); + errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n"; + RtMidi::error( RtError::MEMORY_ERROR, errorString_ ); } } @@ -1532,16 +1832,16 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) for ( unsigned int i=0; i<nBytes; ++i ) data->buffer[i] = message->at(i); result = snd_midi_event_encode( data->coder, data->buffer, (long)nBytes, &ev ); if ( result < (int)nBytes ) { - errorString_ = "RtMidiOut::sendMessage: event parsing error!"; - error( RtError::WARNING ); + errorString_ = "MidiOutAlsa::sendMessage: event parsing error!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } // Send the event. result = snd_seq_event_output(data->seq, &ev); if ( result < 0 ) { - errorString_ = "RtMidiOut::sendMessage: error sending MIDI message to port."; - error( RtError::WARNING ); + errorString_ = "MidiOutAlsa::sendMessage: error sending MIDI message to port."; + RtMidi::error( RtError::WARNING, errorString_ ); } snd_seq_drain_output(data->seq); } @@ -1550,422 +1850,6 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) //*********************************************************************// -// API: IRIX MD -//*********************************************************************// - -// API information gleamed from: -// http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?cmd=getdoc&coll=0650&db=man&fname=3%20mdIntro - -// If the Makefile doesn't work, try the following: -// CC -o midiinfo -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp midiinfo.cpp -lpthread -lmd -// CC -o midiout -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp midiout.cpp -lpthread -lmd -// CC -o qmidiin -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp qmidiin.cpp -lpthread -lmd -// CC -o cmidiin -LANG:std -D__IRIX_MD__ -I../ ../RtMidi.cpp cmidiin.cpp -lpthread -lmd - -#if defined(__IRIX_MD__) - -#include <pthread.h> -#include <sys/time.h> -#include <unistd.h> - -// Irix MIDI header file. -#include <dmedia/midi.h> - -// A structure to hold variables related to the IRIX API -// implementation. -struct IrixMidiData { - MDport port; - pthread_t thread; -}; - -//*********************************************************************// -// API: IRIX -// Class Definitions: RtMidiIn -//*********************************************************************// - -extern "C" void *irixMidiHandler( void *ptr ) -{ - RtMidiIn::RtMidiInData *data = static_cast<RtMidiIn::RtMidiInData *> (ptr); - IrixMidiData *apiData = static_cast<IrixMidiData *> (data->apiData); - - bool continueSysex = false; - unsigned char status; - unsigned short size; - MDevent event; - int fd = mdGetFd( apiData->port ); - if ( fd < 0 ) { - data->doInput = false; - std::cerr << "\nRtMidiIn::irixMidiHandler: error getting port descriptor!\n\n"; - return 0; - } - - fd_set mask, rmask; - FD_ZERO( &mask ); - FD_SET( fd, &mask ); - struct timeval timeout = {0, 0}; - RtMidiIn::MidiMessage message; - int result; - - while ( data->doInput ) { - - rmask = mask; - timeout.tv_sec = 0; - timeout.tv_usec = 0; - if ( select( fd+1, &rmask, NULL, NULL, &timeout ) <= 0 ) { - // No data pending ... sleep a bit. - usleep( 1000 ); - continue; - } - - // If here, there should be data. - result = mdReceive( apiData->port, &event, 1); - if ( result <= 0 ) { - std::cerr << "\nRtMidiIn::irixMidiHandler: MIDI input read error!\n\n"; - continue; - } - - message.timeStamp = event.stamp * 0.000000001; - - size = 0; - status = event.msg[0]; - if ( !(status & 0x80) ) continue; - if ( status == 0xF0 ) { - // Sysex message ... can be segmented across multiple messages. - if ( !(data->ignoreFlags & 0x01) ) { - if ( continueSysex ) { - // We have a continuing, segmented sysex message. Append - // the new bytes to our existing message. - for ( int i=0; i<event.msglen; ++i ) - message.bytes.push_back( event.sysexmsg[i] ); - if ( event.sysexmsg[event.msglen-1] == 0xF7 ) continueSysex = false; - if ( !continueSysex ) { - // If not a continuing sysex message, invoke the user callback function or queue the message. - if ( data->usingCallback && message.bytes.size() > 0 ) { - 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 << "\nRtMidiIn: message queue limit reached!!\n\n"; - } - message.bytes.clear(); - } - } - } - mdFree( NULL ); - continue; - } - else if ( status < 0xC0 ) size = 3; - else if ( status < 0xE0 ) size = 2; - else if ( status < 0xF0 ) size = 3; - else if ( status == 0xF1 && !(data->ignoreFlags & 0x02) ) { - // A MIDI time code message and we're not ignoring it. - size = 2; - } - else if ( status == 0xF2 ) size = 3; - else if ( status == 0xF3 ) size = 2; - else if ( status == 0xF8 ) { - if ( !(data->ignoreFlags & 0x02) ) { - // A MIDI timing tick message and we're not ignoring it. - size = 1; - } - } - else if ( status == 0xFE ) { // MIDI active sensing - if ( !(data->ignoreFlags & 0x04) ) - size = 1; - } - else size = 1; - - // Copy the MIDI data to our vector. - if ( size ) { - message.bytes.assign( &event.msg[0], &event.msg[size] ); - // 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 << "\nRtMidiIn: message queue limit reached!!\n\n"; - } - message.bytes.clear(); - } - } - - return 0; -} - -void RtMidiIn :: initialize( const std::string& /*clientName*/ ) -{ - // Initialize the Irix MIDI system. At the moment, we will not - // worry about a return value of zero (ports) because there is a - // chance the user could plug something in after instantiation. - int nPorts = mdInit(); - - // Create our api-specific connection information. - IrixMidiData *data = (IrixMidiData *) new IrixMidiData; - apiData_ = (void *) data; - inputData_.apiData = (void *) data; -} - -void RtMidiIn :: openPort( unsigned int portNumber, const std::string /*portName*/ ) -{ - if ( connected_ ) { - errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; - error( RtError::WARNING ); - return; - } - - int nPorts = mdInit(); - if (nPorts < 1) { - errorString_ = "RtMidiIn::openPort: no Irix MIDI input sources found!"; - error( RtError::NO_DEVICES_FOUND ); - } - - std::ostringstream ost; - if ( portNumber >= nPorts ) { - ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; - errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); - } - - IrixMidiData *data = static_cast<IrixMidiData *> (apiData_); - data->port = mdOpenInPort( mdGetName(portNumber) ); - if ( data->port == NULL ) { - ost << "RtMidiIn::openPort: Irix error opening the port (" << portNumber << ")."; - errorString_ = ost.str(); - error( RtError::DRIVER_ERROR ); - } - mdSetStampMode(data->port, MD_DELTASTAMP); - - // Start our MIDI input thread. - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); - pthread_attr_setschedpolicy(&attr, SCHED_RR); - - inputData_.doInput = true; - int err = pthread_create(&data->thread, &attr, irixMidiHandler, &inputData_); - pthread_attr_destroy(&attr); - if (err) { - mdClosePort( data->port ); - inputData_.doInput = false; - errorString_ = "RtMidiIn::openPort: error starting MIDI input thread!"; - error( RtError::THREAD_ERROR ); - } - - connected_ = true; -} - -void RtMidiIn :: openVirtualPort( std::string portName ) -{ - // This function cannot be implemented for the Irix MIDI API. - errorString_ = "RtMidiIn::openVirtualPort: cannot be implemented in Irix MIDI API!"; - error( RtError::WARNING ); -} - -void RtMidiIn :: closePort( void ) -{ - if ( connected_ ) { - IrixMidiData *data = static_cast<IrixMidiData *> (apiData_); - mdClosePort( data->port ); - connected_ = false; - - // Shutdown the input thread. - inputData_.doInput = false; - pthread_join( data->thread, NULL ); - } -} - -RtMidiIn :: ~RtMidiIn() -{ - // Close a connection if it exists. - closePort(); - - // Cleanup. - IrixMidiData *data = static_cast<IrixMidiData *> (apiData_); - delete data; - - // Delete the MIDI queue. - if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring; -} - -unsigned int RtMidiIn :: getPortCount() -{ - int nPorts = mdInit(); - if ( nPorts >= 0 ) return nPorts; - else return 0; -} - -std::string RtMidiIn :: getPortName( unsigned int portNumber ) -{ - int nPorts = mdInit(); - - std::string stringName; - std::ostringstream ost; - if ( portNumber >= nPorts ) { - ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; - errorString_ = ost.str(); - //error( RtError::INVALID_PARAMETER ); - error( RtError::WARNING ); - } - else - std::string stringName = std::string( mdGetName( portNumber ) ); - - return stringName; -} - -//*********************************************************************// -// API: IRIX MD -// Class Definitions: RtMidiOut -//*********************************************************************// - -unsigned int RtMidiOut :: getPortCount() -{ - int nPorts = mdInit(); - if ( nPorts >= 0 ) return nPorts; - else return 0; -} - -std::string RtMidiOut :: getPortName( unsigned int portNumber ) -{ - int nPorts = mdInit(); - - std::string stringName; - std::ostringstream ost; - if ( portNumber >= nPorts ) { - ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; - errorString_ = ost.str(); - //error( RtError::INVALID_PARAMETER ); - error( RtError::WARNING ); - } - else - std::string stringName = std::string( mdGetName( portNumber ) ); - - return stringName; -} - -void RtMidiOut :: initialize( const std::string& /*clientName*/ ) -{ - // Initialize the Irix MIDI system. At the moment, we will not - // worry about a return value of zero (ports) because there is a - // chance the user could plug something in after instantiation. - int nPorts = mdInit(); - - // Create our api-specific connection information. - IrixMidiData *data = (IrixMidiData *) new IrixMidiData; - apiData_ = (void *) data; -} - -void RtMidiOut :: openPort( unsigned int portNumber, const std::string /*portName*/ ) -{ - if ( connected_ ) { - errorString_ = "RtMidiOut::openPort: a valid connection already exists!"; - error( RtError::WARNING ); - return; - } - - int nPorts = mdInit(); - if (nPorts < 1) { - errorString_ = "RtMidiOut::openPort: no Irix MIDI output sources found!"; - error( RtError::NO_DEVICES_FOUND ); - } - - std::ostringstream ost; - if ( portNumber >= nPorts ) { - ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; - errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); - } - - IrixMidiData *data = static_cast<IrixMidiData *> (apiData_); - data->port = mdOpenOutPort( mdGetName(portNumber) ); - if ( data->port == NULL ) { - ost << "RtMidiOut::openPort: Irix error opening the port (" << portNumber << ")."; - errorString_ = ost.str(); - error( RtError::DRIVER_ERROR ); - } - mdSetStampMode(data->port, MD_NOSTAMP); - - connected_ = true; -} - -void RtMidiOut :: closePort( void ) -{ - if ( connected_ ) { - IrixMidiData *data = static_cast<IrixMidiData *> (apiData_); - mdClosePort( data->port ); - connected_ = false; - } -} - -void RtMidiOut :: openVirtualPort( std::string portName ) -{ - // This function cannot be implemented for the Irix MIDI API. - errorString_ = "RtMidiOut::openVirtualPort: cannot be implemented in Irix MIDI API!"; - error( RtError::WARNING ); -} - -RtMidiOut :: ~RtMidiOut() -{ - // Close a connection if it exists. - closePort(); - - // Cleanup. - IrixMidiData *data = static_cast<IrixMidiData *> (apiData_); - delete data; -} - -void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) -{ - int result; - MDevent event; - IrixMidiData *data = static_cast<IrixMidiData *> (apiData_); - char *buffer = 0; - - unsigned int nBytes = message->size(); - if ( nBytes == 0 ) return; - event.stamp = 0; - if ( message->at(0) == 0xF0 ) { - if ( nBytes < 3 ) return; // check for bogus sysex - event.msg[0] = 0xF0; - event.msglen = nBytes; - buffer = (char *) malloc( nBytes ); - for ( int i=0; i<nBytes; ++i ) buffer[i] = message->at(i); - event.sysexmsg = buffer; - } - else { - for ( int i=0; i<nBytes; ++i ) - event.msg[i] = message->at(i); - } - - // Send the event. - result = mdSend( data->port, &event, 1 ); - if ( buffer ) free( buffer ); - if ( result < 1 ) { - errorString_ = "RtMidiOut::sendMessage: IRIX error sending MIDI message!"; - error( RtError::WARNING ); - return; - } -} - -#endif // __IRIX_MD__ - -//*********************************************************************// // API: Windows Multimedia Library (MM) //*********************************************************************// @@ -1993,13 +1877,13 @@ struct WinMidiData { HMIDIIN inHandle; // Handle to Midi Input Device HMIDIOUT outHandle; // Handle to Midi Output Device DWORD lastTime; - RtMidiIn::MidiMessage message; + MidiInApi::MidiMessage message; LPMIDIHDR sysexBuffer[RT_SYSEX_BUFFER_COUNT]; }; //*********************************************************************// // API: Windows MM -// Class Definitions: RtMidiIn +// Class Definitions: MidiInWinMM //*********************************************************************// static void CALLBACK midiInputCallback( HMIDIIN hmin, @@ -2010,13 +1894,15 @@ static void CALLBACK midiInputCallback( HMIDIIN hmin, { if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA && inputStatus != MIM_LONGERROR ) return; - //RtMidiIn::RtMidiInData *data = static_cast<RtMidiIn::RtMidiInData *> (instancePtr); - RtMidiIn::RtMidiInData *data = (RtMidiIn::RtMidiInData *)instancePtr; + //MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (instancePtr); + MidiInApi::RtMidiInData *data = (MidiInApi::RtMidiInData *)instancePtr; WinMidiData *apiData = static_cast<WinMidiData *> (data->apiData); // Calculate time stamp. - apiData->message.timeStamp = 0.0; - if ( data->firstMessage == true ) data->firstMessage = false; + if ( data->firstMessage == true ) { + apiData->message.timeStamp = 0.0; + data->firstMessage = false; + } else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001; apiData->lastTime = timestamp; @@ -2097,14 +1983,29 @@ static void CALLBACK midiInputCallback( HMIDIIN hmin, apiData->message.bytes.clear(); } -void RtMidiIn :: initialize( const std::string& /*clientName*/ ) +MidiInWinMM :: MidiInWinMM( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit ) +{ + initialize( clientName ); +} + +MidiInWinMM :: ~MidiInWinMM() +{ + // Close a connection if it exists. + closePort(); + + // Cleanup. + WinMidiData *data = static_cast<WinMidiData *> (apiData_); + delete data; +} + +void MidiInWinMM :: initialize( const std::string& /*clientName*/ ) { // We'll issue a warning here if no devices are available but not // throw an error since the user can plugin something later. unsigned int nDevices = midiInGetNumDevs(); if ( nDevices == 0 ) { - errorString_ = "RtMidiIn::initialize: no MIDI input devices currently available."; - error( RtError::WARNING ); + errorString_ = "MidiInWinMM::initialize: no MIDI input devices currently available."; + RtMidi::error( RtError::WARNING, errorString_ ); } // Save our api-specific connection information. @@ -2114,25 +2015,25 @@ void RtMidiIn :: initialize( const std::string& /*clientName*/ ) data->message.bytes.clear(); // needs to be empty for first input message } -void RtMidiIn :: openPort( unsigned int portNumber, const std::string /*portName*/ ) +void MidiInWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ ) { if ( connected_ ) { - errorString_ = "RtMidiIn::openPort: a valid connection already exists!"; - error( RtError::WARNING ); + errorString_ = "MidiInWinMM::openPort: a valid connection already exists!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } unsigned int nDevices = midiInGetNumDevs(); if (nDevices == 0) { - errorString_ = "RtMidiIn::openPort: no MIDI input sources found!"; - error( RtError::NO_DEVICES_FOUND ); + errorString_ = "MidiInWinMM::openPort: no MIDI input sources found!"; + RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ ); } std::ostringstream ost; if ( portNumber >= nDevices ) { - ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiInWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); + RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); } WinMidiData *data = static_cast<WinMidiData *> (apiData_); @@ -2142,8 +2043,8 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string /*portName (DWORD_PTR)&inputData_, CALLBACK_FUNCTION ); if ( result != MMSYSERR_NOERROR ) { - errorString_ = "RtMidiIn::openPort: error creating Windows MM MIDI input port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInWinMM::openPort: error creating Windows MM MIDI input port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Allocate and init the sysex buffers. @@ -2157,37 +2058,37 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string /*portName result = midiInPrepareHeader( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); - errorString_ = "RtMidiIn::openPort: error starting Windows MM MIDI input port (PrepareHeader)."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (PrepareHeader)."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Register the buffer. result = midiInAddBuffer( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); - errorString_ = "RtMidiIn::openPort: error starting Windows MM MIDI input port (AddBuffer)."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (AddBuffer)."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } result = midiInStart( data->inHandle ); if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); - errorString_ = "RtMidiIn::openPort: error starting Windows MM MIDI input port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } connected_ = true; } -void RtMidiIn :: openVirtualPort( std::string portName ) +void MidiInWinMM :: openVirtualPort( std::string portName ) { // This function cannot be implemented for the Windows MM MIDI API. - errorString_ = "RtMidiIn::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; - error( RtError::WARNING ); + errorString_ = "MidiInWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; + RtMidi::error( RtError::WARNING, errorString_ ); } -void RtMidiIn :: closePort( void ) +void MidiInWinMM :: closePort( void ) { if ( connected_ ) { WinMidiData *data = static_cast<WinMidiData *> (apiData_); @@ -2200,8 +2101,8 @@ void RtMidiIn :: closePort( void ) delete [] data->sysexBuffer[i]; if ( result != MMSYSERR_NOERROR ) { midiInClose( data->inHandle ); - errorString_ = "RtMidiIn::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader)."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInWinMM::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader)."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } @@ -2210,34 +2111,21 @@ void RtMidiIn :: closePort( void ) } } -RtMidiIn :: ~RtMidiIn() -{ - // Close a connection if it exists. - closePort(); - - // Cleanup. - WinMidiData *data = static_cast<WinMidiData *> (apiData_); - delete data; - - // Delete the MIDI queue. - if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring; -} - -unsigned int RtMidiIn :: getPortCount() +unsigned int MidiInWinMM :: getPortCount() { return midiInGetNumDevs(); } -std::string RtMidiIn :: getPortName( unsigned int portNumber ) +std::string MidiInWinMM :: getPortName( unsigned int portNumber ) { std::string stringName; unsigned int nDevices = midiInGetNumDevs(); if ( portNumber >= nDevices ) { std::ostringstream ost; - ost << "RtMidiIn::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiInWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - //error( RtError::INVALID_PARAMETER ); - error( RtError::WARNING ); + //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); + RtMidi::error( RtError::WARNING, errorString_ ); return stringName; } @@ -2252,29 +2140,67 @@ std::string RtMidiIn :: getPortName( unsigned int portNumber ) stringName = std::string( deviceCaps.szPname ); #endif + // Next lines added to add the portNumber to the name so that + // the device's names are sure to be listed with individual names + // even when they have the same brand name + std::ostringstream os; + os << " "; + os << portNumber; + stringName += os.str(); + return stringName; } //*********************************************************************// // API: Windows MM -// Class Definitions: RtMidiOut +// Class Definitions: MidiOutWinMM //*********************************************************************// -unsigned int RtMidiOut :: getPortCount() +MidiOutWinMM :: MidiOutWinMM( const std::string clientName ) : MidiOutApi() +{ + initialize( clientName ); +} + +MidiOutWinMM :: ~MidiOutWinMM() +{ + // Close a connection if it exists. + closePort(); + + // Cleanup. + WinMidiData *data = static_cast<WinMidiData *> (apiData_); + delete data; +} + +void MidiOutWinMM :: initialize( const std::string& /*clientName*/ ) +{ + // We'll issue a warning here if no devices are available but not + // throw an error since the user can plug something in later. + unsigned int nDevices = midiOutGetNumDevs(); + if ( nDevices == 0 ) { + errorString_ = "MidiOutWinMM::initialize: no MIDI output devices currently available."; + RtMidi::error( RtError::WARNING, errorString_ ); + } + + // Save our api-specific connection information. + WinMidiData *data = (WinMidiData *) new WinMidiData; + apiData_ = (void *) data; +} + +unsigned int MidiOutWinMM :: getPortCount() { return midiOutGetNumDevs(); } -std::string RtMidiOut :: getPortName( unsigned int portNumber ) +std::string MidiOutWinMM :: getPortName( unsigned int portNumber ) { std::string stringName; unsigned int nDevices = midiOutGetNumDevs(); if ( portNumber >= nDevices ) { std::ostringstream ost; - ost << "RtMidiOut::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiOutWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - //error( RtError::INVALID_PARAMETER ); - error( RtError::WARNING ); + //RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); + RtMidi::error( RtError::WARNING, errorString_ ); return stringName; } @@ -2292,40 +2218,25 @@ std::string RtMidiOut :: getPortName( unsigned int portNumber ) return stringName; } -void RtMidiOut :: initialize( const std::string& /*clientName*/ ) -{ - // We'll issue a warning here if no devices are available but not - // throw an error since the user can plug something in later. - unsigned int nDevices = midiOutGetNumDevs(); - if ( nDevices == 0 ) { - errorString_ = "RtMidiOut::initialize: no MIDI output devices currently available."; - error( RtError::WARNING ); - } - - // Save our api-specific connection information. - WinMidiData *data = (WinMidiData *) new WinMidiData; - apiData_ = (void *) data; -} - -void RtMidiOut :: openPort( unsigned int portNumber, const std::string /*portName*/ ) +void MidiOutWinMM :: openPort( unsigned int portNumber, const std::string /*portName*/ ) { if ( connected_ ) { - errorString_ = "RtMidiOut::openPort: a valid connection already exists!"; - error( RtError::WARNING ); + errorString_ = "MidiOutWinMM::openPort: a valid connection already exists!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } unsigned int nDevices = midiOutGetNumDevs(); if (nDevices < 1) { - errorString_ = "RtMidiOut::openPort: no MIDI output destinations found!"; - error( RtError::NO_DEVICES_FOUND ); + errorString_ = "MidiOutWinMM::openPort: no MIDI output destinations found!"; + RtMidi::error( RtError::NO_DEVICES_FOUND, errorString_ ); } std::ostringstream ost; if ( portNumber >= nDevices ) { - ost << "RtMidiOut::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiOutWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::INVALID_PARAMETER ); + RtMidi::error( RtError::INVALID_PARAMETER, errorString_ ); } WinMidiData *data = static_cast<WinMidiData *> (apiData_); @@ -2335,14 +2246,14 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string /*portNam (DWORD)NULL, CALLBACK_NULL ); if ( result != MMSYSERR_NOERROR ) { - errorString_ = "RtMidiOut::openPort: error creating Windows MM MIDI output port."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutWinMM::openPort: error creating Windows MM MIDI output port."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } connected_ = true; } -void RtMidiOut :: closePort( void ) +void MidiOutWinMM :: closePort( void ) { if ( connected_ ) { WinMidiData *data = static_cast<WinMidiData *> (apiData_); @@ -2352,29 +2263,19 @@ void RtMidiOut :: closePort( void ) } } -void RtMidiOut :: openVirtualPort( std::string portName ) +void MidiOutWinMM :: openVirtualPort( std::string portName ) { // This function cannot be implemented for the Windows MM MIDI API. - errorString_ = "RtMidiOut::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; - error( RtError::WARNING ); -} - -RtMidiOut :: ~RtMidiOut() -{ - // Close a connection if it exists. - closePort(); - - // Cleanup. - WinMidiData *data = static_cast<WinMidiData *> (apiData_); - delete data; + errorString_ = "MidiOutWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; + RtMidi::error( RtError::WARNING, errorString_ ); } -void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) +void MidiOutWinMM :: sendMessage( std::vector<unsigned char> *message ) { unsigned int nBytes = static_cast<unsigned int>(message->size()); if ( nBytes == 0 ) { - errorString_ = "RtMidiOut::sendMessage: message argument is empty!"; - error( RtError::WARNING ); + errorString_ = "MidiOutWinMM::sendMessage: message argument is empty!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } @@ -2385,8 +2286,8 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) // Allocate buffer for sysex data. char *buffer = (char *) malloc( nBytes ); if ( buffer == NULL ) { - errorString_ = "RtMidiOut::sendMessage: error allocating sysex message memory!"; - error( RtError::MEMORY_ERROR ); + errorString_ = "MidiOutWinMM::sendMessage: error allocating sysex message memory!"; + RtMidi::error( RtError::MEMORY_ERROR, errorString_ ); } // Copy data to buffer. @@ -2400,16 +2301,16 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) result = midiOutPrepareHeader( data->outHandle, &sysex, sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { free( buffer ); - errorString_ = "RtMidiOut::sendMessage: error preparing sysex header."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutWinMM::sendMessage: error preparing sysex header."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Send the message. result = midiOutLongMsg( data->outHandle, &sysex, sizeof(MIDIHDR) ); if ( result != MMSYSERR_NOERROR ) { free( buffer ); - errorString_ = "RtMidiOut::sendMessage: error sending sysex message."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutWinMM::sendMessage: error sending sysex message."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Unprepare the buffer and MIDIHDR. @@ -2421,8 +2322,8 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) // Make sure the message size isn't too big. if ( nBytes > 3 ) { - errorString_ = "RtMidiOut::sendMessage: message size is greater than 3 bytes (and not sysex)!"; - error( RtError::WARNING ); + errorString_ = "MidiOutWinMM::sendMessage: message size is greater than 3 bytes (and not sysex)!"; + RtMidi::error( RtError::WARNING, errorString_ ); return; } @@ -2437,23 +2338,1050 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) // Send the message immediately. result = midiOutShortMsg( data->outHandle, packet ); if ( result != MMSYSERR_NOERROR ) { - errorString_ = "RtMidiOut::sendMessage: error sending MIDI message."; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutWinMM::sendMessage: error sending MIDI message."; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } } #endif // __WINDOWS_MM__ +// *********************************************************************// +// API: WINDOWS Kernel Streaming +// +// Written by Sebastien Alaiwan, 2012. +// +// NOTE BY GARY: much of the KS-specific code below probably should go in a separate file. +// +// *********************************************************************// + +#if defined(__WINDOWS_KS__) + +#include <string> +#include <vector> +#include <memory> +#include <stdexcept> +#include <sstream> +#include <windows.h> +#include <setupapi.h> +#include <mmsystem.h> + +#include "include/ks.h" +#include "include/ksmedia.h" + +#define INSTANTIATE_GUID(a) GUID const a = { STATIC_ ## a } + +INSTANTIATE_GUID(GUID_NULL); +INSTANTIATE_GUID(KSPROPSETID_Pin); +INSTANTIATE_GUID(KSPROPSETID_Connection); +INSTANTIATE_GUID(KSPROPSETID_Topology); +INSTANTIATE_GUID(KSINTERFACESETID_Standard); +INSTANTIATE_GUID(KSMEDIUMSETID_Standard); +INSTANTIATE_GUID(KSDATAFORMAT_TYPE_MUSIC); +INSTANTIATE_GUID(KSDATAFORMAT_SUBTYPE_MIDI); +INSTANTIATE_GUID(KSDATAFORMAT_SPECIFIER_NONE); + +#undef INSTANTIATE_GUID + +typedef std::basic_string<TCHAR> tstring; + +inline bool IsValid(HANDLE handle) +{ + return handle != NULL && handle != INVALID_HANDLE_VALUE; +} + +class ComException : public std::runtime_error +{ +private: + static std::string MakeString(std::string const& s, HRESULT hr) + { + std::stringstream ss; + ss << "(error 0x" << std::hex << hr << ")"; + return s + ss.str(); + } + +public: + ComException(std::string const& s, HRESULT hr) : + std::runtime_error(MakeString(s, hr)) + { + } +}; + +template<typename TFilterType> +class CKsEnumFilters +{ +public: + ~CKsEnumFilters() + { + DestroyLists(); + } + + void EnumFilters(GUID const* categories, size_t numCategories) + { + DestroyLists(); + + if (categories == 0) + throw std::runtime_error("CKsEnumFilters: invalid argument"); + + // Get a handle to the device set specified by the guid + HDEVINFO hDevInfo = ::SetupDiGetClassDevs(&categories[0], NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); + if (!IsValid(hDevInfo)) + throw std::runtime_error("CKsEnumFilters: no devices found"); + + // Loop through members of the set and get details for each + for (int iClassMember=0;;iClassMember++) { + try { + SP_DEVICE_INTERFACE_DATA DID; + DID.cbSize = sizeof(DID); + DID.Reserved = 0; + + bool fRes = ::SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &categories[0], iClassMember, &DID); + if (!fRes) + break; + + // Get filter friendly name + HKEY hRegKey = ::SetupDiOpenDeviceInterfaceRegKey(hDevInfo, &DID, 0, KEY_READ); + if (hRegKey == INVALID_HANDLE_VALUE) + throw std::runtime_error("CKsEnumFilters: interface has no registry"); + + char friendlyName[256]; + DWORD dwSize = sizeof friendlyName; + LONG lval = ::RegQueryValueEx(hRegKey, TEXT("FriendlyName"), NULL, NULL, (LPBYTE)friendlyName, &dwSize); + ::RegCloseKey(hRegKey); + if (lval != ERROR_SUCCESS) + throw std::runtime_error("CKsEnumFilters: interface has no friendly name"); + + // Get details for the device registered in this class + DWORD const cbItfDetails = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + MAX_PATH * sizeof(WCHAR); + std::vector<BYTE> buffer(cbItfDetails); + + SP_DEVICE_INTERFACE_DETAIL_DATA* pDevInterfaceDetails = reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(&buffer[0]); + pDevInterfaceDetails->cbSize = sizeof(*pDevInterfaceDetails); + + SP_DEVINFO_DATA DevInfoData; + DevInfoData.cbSize = sizeof(DevInfoData); + DevInfoData.Reserved = 0; + + fRes = ::SetupDiGetDeviceInterfaceDetail(hDevInfo, &DID, pDevInterfaceDetails, cbItfDetails, NULL, &DevInfoData); + if (!fRes) + throw std::runtime_error("CKsEnumFilters: could not get interface details"); + + // check additional category guids which may (or may not) have been supplied + for (size_t i=1; i < numCategories; ++i) { + SP_DEVICE_INTERFACE_DATA DIDAlias; + DIDAlias.cbSize = sizeof(DIDAlias); + DIDAlias.Reserved = 0; + + fRes = ::SetupDiGetDeviceInterfaceAlias(hDevInfo, &DID, &categories[i], &DIDAlias); + if (!fRes) + throw std::runtime_error("CKsEnumFilters: could not get interface alias"); + + // Check if the this interface alias is enabled. + if (!DIDAlias.Flags || (DIDAlias.Flags & SPINT_REMOVED)) + throw std::runtime_error("CKsEnumFilters: interface alias is not enabled"); + } + + std::auto_ptr<TFilterType> pFilter(new TFilterType(pDevInterfaceDetails->DevicePath, friendlyName)); + + pFilter->Instantiate(); + pFilter->FindMidiPins(); + pFilter->Validate(); + + m_Filters.push_back(pFilter.release()); + } + catch (std::runtime_error const& e) { + } + } + + ::SetupDiDestroyDeviceInfoList(hDevInfo); + } + +private: + void DestroyLists() + { + for (size_t i=0;i < m_Filters.size();++i) + delete m_Filters[i]; + m_Filters.clear(); + } + +public: + // TODO: make this private. + std::vector<TFilterType*> m_Filters; +}; + +class CKsObject +{ +public: + CKsObject(HANDLE handle) : m_handle(handle) + { + } + +protected: + HANDLE m_handle; + + void SetProperty(REFGUID guidPropertySet, ULONG nProperty, void* pvValue, ULONG cbValue) + { + KSPROPERTY ksProperty; + memset(&ksProperty, 0, sizeof ksProperty); + ksProperty.Set = guidPropertySet; + ksProperty.Id = nProperty; + ksProperty.Flags = KSPROPERTY_TYPE_SET; + + HRESULT hr = DeviceIoControlKsProperty(ksProperty, pvValue, cbValue); + if (FAILED(hr)) + throw ComException("CKsObject::SetProperty: could not set property", hr); + } + +private: + + HRESULT DeviceIoControlKsProperty(KSPROPERTY& ksProperty, void* pvValue, ULONG cbValue) + { + ULONG ulReturned; + return ::DeviceIoControl( + m_handle, + IOCTL_KS_PROPERTY, + &ksProperty, + sizeof(ksProperty), + pvValue, + cbValue, + &ulReturned, + NULL); + } +}; + +class CKsPin; + +class CKsFilter : public CKsObject +{ + friend class CKsPin; + +public: + CKsFilter(tstring const& name, std::string const& sFriendlyName); + virtual ~CKsFilter(); + + virtual void Instantiate(); + + template<typename T> + T GetPinProperty(ULONG nPinId, ULONG nProperty) + { + ULONG ulReturned = 0; + T value; + + KSP_PIN ksPProp; + ksPProp.Property.Set = KSPROPSETID_Pin; + ksPProp.Property.Id = nProperty; + ksPProp.Property.Flags = KSPROPERTY_TYPE_GET; + ksPProp.PinId = nPinId; + ksPProp.Reserved = 0; + + HRESULT hr = ::DeviceIoControl( + m_handle, + IOCTL_KS_PROPERTY, + &ksPProp, + sizeof(KSP_PIN), + &value, + sizeof(value), + &ulReturned, + NULL); + if (FAILED(hr)) + throw ComException("CKsFilter::GetPinProperty: failed to retrieve property", hr); + + return value; + } + + void GetPinPropertyMulti(ULONG nPinId, REFGUID guidPropertySet, ULONG nProperty, PKSMULTIPLE_ITEM* ppKsMultipleItem) + { + HRESULT hr; + + KSP_PIN ksPProp; + ksPProp.Property.Set = guidPropertySet; + ksPProp.Property.Id = nProperty; + ksPProp.Property.Flags = KSPROPERTY_TYPE_GET; + ksPProp.PinId = nPinId; + ksPProp.Reserved = 0; + + ULONG cbMultipleItem = 0; + hr = ::DeviceIoControl(m_handle, + IOCTL_KS_PROPERTY, + &ksPProp.Property, + sizeof(KSP_PIN), + NULL, + 0, + &cbMultipleItem, + NULL); + if (FAILED(hr)) + throw ComException("CKsFilter::GetPinPropertyMulti: cannot get property", hr); + + *ppKsMultipleItem = (PKSMULTIPLE_ITEM) new BYTE[cbMultipleItem]; + + ULONG ulReturned = 0; + hr = ::DeviceIoControl( + m_handle, + IOCTL_KS_PROPERTY, + &ksPProp, + sizeof(KSP_PIN), + (PVOID)*ppKsMultipleItem, + cbMultipleItem, + &ulReturned, + NULL); + if (FAILED(hr)) + throw ComException("CKsFilter::GetPinPropertyMulti: cannot get property", hr); + } + + std::string const& GetFriendlyName() const + { + return m_sFriendlyName; + } + +protected: + + std::vector<CKsPin*> m_Pins; // this list owns the pins. + + std::vector<CKsPin*> m_RenderPins; + std::vector<CKsPin*> m_CapturePins; + +private: + std::string const m_sFriendlyName; // friendly name eg "Virus TI Synth" + tstring const m_sName; // Filter path, eg "\\?\usb#vid_133e&pid_0815...\vtimidi02" +}; + +class CKsPin : public CKsObject +{ +public: + CKsPin(CKsFilter* pFilter, ULONG nId); + virtual ~CKsPin(); + + virtual void Instantiate(); + + void ClosePin(); + + void SetState(KSSTATE ksState); + + void WriteData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED); + void ReadData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED); + + KSPIN_DATAFLOW GetDataFlow() const + { + return m_DataFlow; + } + + bool IsSink() const + { + return m_Communication == KSPIN_COMMUNICATION_SINK + || m_Communication == KSPIN_COMMUNICATION_BOTH; + } + + +protected: + PKSPIN_CONNECT m_pKsPinConnect; // creation parameters of pin + CKsFilter* const m_pFilter; + + ULONG m_cInterfaces; + PKSIDENTIFIER m_pInterfaces; + PKSMULTIPLE_ITEM m_pmiInterfaces; + + ULONG m_cMediums; + PKSIDENTIFIER m_pMediums; + PKSMULTIPLE_ITEM m_pmiMediums; + + ULONG m_cDataRanges; + PKSDATARANGE m_pDataRanges; + PKSMULTIPLE_ITEM m_pmiDataRanges; + + KSPIN_DATAFLOW m_DataFlow; + KSPIN_COMMUNICATION m_Communication; +}; + +CKsFilter::CKsFilter(tstring const& sName, std::string const& sFriendlyName) : + CKsObject(INVALID_HANDLE_VALUE), + m_sFriendlyName(sFriendlyName), + m_sName(sName) +{ + if (sName.empty()) + throw std::runtime_error("CKsFilter::CKsFilter: name can't be empty"); +} + +CKsFilter::~CKsFilter() +{ + for (size_t i=0;i < m_Pins.size();++i) + delete m_Pins[i]; + + if (IsValid(m_handle)) + ::CloseHandle(m_handle); +} + +void CKsFilter::Instantiate() +{ + m_handle = CreateFile( + m_sName.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + NULL); + + if (!IsValid(m_handle)) + { + DWORD const dwError = GetLastError(); + throw ComException("CKsFilter::Instantiate: can't open driver", HRESULT_FROM_WIN32(dwError)); + } +} + +CKsPin::CKsPin(CKsFilter* pFilter, ULONG PinId) : + CKsObject(INVALID_HANDLE_VALUE), + m_pKsPinConnect(NULL), + m_pFilter(pFilter) +{ + m_Communication = m_pFilter->GetPinProperty<KSPIN_COMMUNICATION>(PinId, KSPROPERTY_PIN_COMMUNICATION); + m_DataFlow = m_pFilter->GetPinProperty<KSPIN_DATAFLOW>(PinId, KSPROPERTY_PIN_DATAFLOW); + + // Interfaces + m_pFilter->GetPinPropertyMulti( + PinId, + KSPROPSETID_Pin, + KSPROPERTY_PIN_INTERFACES, + &m_pmiInterfaces); + + m_cInterfaces = m_pmiInterfaces->Count; + m_pInterfaces = (PKSPIN_INTERFACE)(m_pmiInterfaces + 1); + + // Mediums + m_pFilter->GetPinPropertyMulti( + PinId, + KSPROPSETID_Pin, + KSPROPERTY_PIN_MEDIUMS, + &m_pmiMediums); + + m_cMediums = m_pmiMediums->Count; + m_pMediums = (PKSPIN_MEDIUM)(m_pmiMediums + 1); + + // Data ranges + m_pFilter->GetPinPropertyMulti( + PinId, + KSPROPSETID_Pin, + KSPROPERTY_PIN_DATARANGES, + &m_pmiDataRanges); + + m_cDataRanges = m_pmiDataRanges->Count; + m_pDataRanges = (PKSDATARANGE)(m_pmiDataRanges + 1); +} + +CKsPin::~CKsPin() +{ + ClosePin(); + + delete[] (BYTE*)m_pKsPinConnect; + delete[] (BYTE*)m_pmiDataRanges; + delete[] (BYTE*)m_pmiInterfaces; + delete[] (BYTE*)m_pmiMediums; +} + +void CKsPin::ClosePin() +{ + if (IsValid(m_handle)) { + SetState(KSSTATE_STOP); + ::CloseHandle(m_handle); + } + m_handle = INVALID_HANDLE_VALUE; +} + +void CKsPin::SetState(KSSTATE ksState) +{ + SetProperty(KSPROPSETID_Connection, KSPROPERTY_CONNECTION_STATE, &ksState, sizeof(ksState)); +} + +void CKsPin::Instantiate() +{ + if (!m_pKsPinConnect) + throw std::runtime_error("CKsPin::Instanciate: abstract pin"); + + DWORD const dwResult = KsCreatePin(m_pFilter->m_handle, m_pKsPinConnect, GENERIC_WRITE | GENERIC_READ, &m_handle); + if (dwResult != ERROR_SUCCESS) + throw ComException("CKsMidiCapFilter::CreateRenderPin: Pin instanciation failed", HRESULT_FROM_WIN32(dwResult)); +} + +void CKsPin::WriteData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED) +{ + DWORD cbWritten; + BOOL fRes = ::DeviceIoControl( + m_handle, + IOCTL_KS_WRITE_STREAM, + NULL, + 0, + pKSSTREAM_HEADER, + pKSSTREAM_HEADER->Size, + &cbWritten, + pOVERLAPPED); + if (!fRes) { + DWORD const dwError = GetLastError(); + if (dwError != ERROR_IO_PENDING) + throw ComException("CKsPin::WriteData: DeviceIoControl failed", HRESULT_FROM_WIN32(dwError)); + } +} + +void CKsPin::ReadData(KSSTREAM_HEADER* pKSSTREAM_HEADER, OVERLAPPED* pOVERLAPPED) +{ + DWORD cbReturned; + BOOL fRes = ::DeviceIoControl( + m_handle, + IOCTL_KS_READ_STREAM, + NULL, + 0, + pKSSTREAM_HEADER, + pKSSTREAM_HEADER->Size, + &cbReturned, + pOVERLAPPED); + if (!fRes) { + DWORD const dwError = GetLastError(); + if (dwError != ERROR_IO_PENDING) + throw ComException("CKsPin::ReadData: DeviceIoControl failed", HRESULT_FROM_WIN32(dwError)); + } +} + +class CKsMidiFilter : public CKsFilter +{ +public: + void FindMidiPins(); + +protected: + CKsMidiFilter(tstring const& sPath, std::string const& sFriendlyName); +}; + +class CKsMidiPin : public CKsPin +{ +public: + CKsMidiPin(CKsFilter* pFilter, ULONG nId); +}; + +class CKsMidiRenFilter : public CKsMidiFilter +{ +public: + CKsMidiRenFilter(tstring const& sPath, std::string const& sFriendlyName); + CKsMidiPin* CreateRenderPin(); + + void Validate() + { + if (m_RenderPins.empty()) + throw std::runtime_error("Could not find a MIDI render pin"); + } +}; + +class CKsMidiCapFilter : public CKsMidiFilter +{ +public: + CKsMidiCapFilter(tstring const& sPath, std::string const& sFriendlyName); + CKsMidiPin* CreateCapturePin(); + + void Validate() + { + if (m_CapturePins.empty()) + throw std::runtime_error("Could not find a MIDI capture pin"); + } +}; + +CKsMidiFilter::CKsMidiFilter(tstring const& sPath, std::string const& sFriendlyName) : + CKsFilter(sPath, sFriendlyName) +{ +} + +void CKsMidiFilter::FindMidiPins() +{ + ULONG numPins = GetPinProperty<ULONG>(0, KSPROPERTY_PIN_CTYPES); + + for (ULONG iPin = 0; iPin < numPins; ++iPin) { + try { + KSPIN_COMMUNICATION com = GetPinProperty<KSPIN_COMMUNICATION>(iPin, KSPROPERTY_PIN_COMMUNICATION); + if (com != KSPIN_COMMUNICATION_SINK && com != KSPIN_COMMUNICATION_BOTH) + throw std::runtime_error("Unknown pin communication value"); + + m_Pins.push_back(new CKsMidiPin(this, iPin)); + } + catch (std::runtime_error const&) { + // pin instanciation has failed, continue to the next pin. + } + } + + m_RenderPins.clear(); + m_CapturePins.clear(); + + for (size_t i = 0; i < m_Pins.size(); ++i) { + CKsPin* const pPin = m_Pins[i]; + + if (pPin->IsSink()) { + if (pPin->GetDataFlow() == KSPIN_DATAFLOW_IN) + m_RenderPins.push_back(pPin); + else + m_CapturePins.push_back(pPin); + } + } + + if (m_RenderPins.empty() && m_CapturePins.empty()) + throw std::runtime_error("No valid pins found on the filter."); +} + +CKsMidiRenFilter::CKsMidiRenFilter(tstring const& sPath, std::string const& sFriendlyName) : + CKsMidiFilter(sPath, sFriendlyName) +{ +} + +CKsMidiPin* CKsMidiRenFilter::CreateRenderPin() +{ + if (m_RenderPins.empty()) + throw std::runtime_error("Could not find a MIDI render pin"); + + CKsMidiPin* pPin = (CKsMidiPin*)m_RenderPins[0]; + pPin->Instantiate(); + return pPin; +} + +CKsMidiCapFilter::CKsMidiCapFilter(tstring const& sPath, std::string const& sFriendlyName) : + CKsMidiFilter(sPath, sFriendlyName) +{ +} + +CKsMidiPin* CKsMidiCapFilter::CreateCapturePin() +{ + if (m_CapturePins.empty()) + throw std::runtime_error("Could not find a MIDI capture pin"); + + CKsMidiPin* pPin = (CKsMidiPin*)m_CapturePins[0]; + pPin->Instantiate(); + return pPin; +} + +CKsMidiPin::CKsMidiPin(CKsFilter* pFilter, ULONG nId) : + CKsPin(pFilter, nId) +{ + DWORD const cbPinCreateSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT); + m_pKsPinConnect = (PKSPIN_CONNECT) new BYTE[cbPinCreateSize]; + + m_pKsPinConnect->Interface.Set = KSINTERFACESETID_Standard; + m_pKsPinConnect->Interface.Id = KSINTERFACE_STANDARD_STREAMING; + m_pKsPinConnect->Interface.Flags = 0; + m_pKsPinConnect->Medium.Set = KSMEDIUMSETID_Standard; + m_pKsPinConnect->Medium.Id = KSMEDIUM_TYPE_ANYINSTANCE; + m_pKsPinConnect->Medium.Flags = 0; + m_pKsPinConnect->PinId = nId; + m_pKsPinConnect->PinToHandle = NULL; + m_pKsPinConnect->Priority.PriorityClass = KSPRIORITY_NORMAL; + m_pKsPinConnect->Priority.PrioritySubClass = 1; + + // point m_pDataFormat to just after the pConnect struct + KSDATAFORMAT* m_pDataFormat = (KSDATAFORMAT*)(m_pKsPinConnect + 1); + m_pDataFormat->FormatSize = sizeof(KSDATAFORMAT); + m_pDataFormat->Flags = 0; + m_pDataFormat->SampleSize = 0; + m_pDataFormat->Reserved = 0; + m_pDataFormat->MajorFormat = GUID(KSDATAFORMAT_TYPE_MUSIC); + m_pDataFormat->SubFormat = GUID(KSDATAFORMAT_SUBTYPE_MIDI); + m_pDataFormat->Specifier = GUID(KSDATAFORMAT_SPECIFIER_NONE); + + bool hasStdStreamingInterface = false; + bool hasStdStreamingMedium = false; + + for ( ULONG i = 0; i < m_cInterfaces; i++ ) { + if (m_pInterfaces[i].Set == KSINTERFACESETID_Standard + && m_pInterfaces[i].Id == KSINTERFACE_STANDARD_STREAMING) + hasStdStreamingInterface = true; + } + + for (ULONG i = 0; i < m_cMediums; i++) { + if (m_pMediums[i].Set == KSMEDIUMSETID_Standard + && m_pMediums[i].Id == KSMEDIUM_STANDARD_DEVIO) + hasStdStreamingMedium = true; + } + + if (!hasStdStreamingInterface) // No standard streaming interfaces on the pin + throw std::runtime_error("CKsMidiPin::CKsMidiPin: no standard streaming interface"); + + if (!hasStdStreamingMedium) // No standard streaming mediums on the pin + throw std::runtime_error("CKsMidiPin::CKsMidiPin: no standard streaming medium"); + + bool hasMidiDataRange = false; + + BYTE const* pDataRangePtr = reinterpret_cast<BYTE const*>(m_pDataRanges); + + for (ULONG i = 0; i < m_cDataRanges; ++i) { + KSDATARANGE const* pDataRange = reinterpret_cast<KSDATARANGE const*>(pDataRangePtr); + + if (pDataRange->SubFormat == KSDATAFORMAT_SUBTYPE_MIDI) { + hasMidiDataRange = true; + break; + } + + pDataRangePtr += pDataRange->FormatSize; + } + + if (!hasMidiDataRange) // No MIDI dataranges on the pin + throw std::runtime_error("CKsMidiPin::CKsMidiPin: no MIDI datarange"); +} + + +struct WindowsKsData +{ + WindowsKsData() : m_pPin(NULL), m_Buffer(1024), m_hInputThread(NULL) + { + memset(&overlapped, 0, sizeof(OVERLAPPED)); + m_hExitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + overlapped.hEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); + m_hInputThread = NULL; + } + + ~WindowsKsData() + { + ::CloseHandle(overlapped.hEvent); + ::CloseHandle(m_hExitEvent); + } + + OVERLAPPED overlapped; + CKsPin* m_pPin; + std::vector<unsigned char> m_Buffer; + std::auto_ptr<CKsEnumFilters<CKsMidiCapFilter> > m_pCaptureEnum; + std::auto_ptr<CKsEnumFilters<CKsMidiRenFilter> > m_pRenderEnum; + HANDLE m_hInputThread; + HANDLE m_hExitEvent; +}; + +// *********************************************************************// +// API: WINDOWS Kernel Streaming +// Class Definitions: MidiInWinKS +// *********************************************************************// + +DWORD WINAPI midiKsInputThread(VOID* pUser) +{ + MidiInApi::RtMidiInData* data = static_cast<MidiInApi::RtMidiInData*>(pUser); + WindowsKsData* apiData = static_cast<WindowsKsData*>(data->apiData); + + HANDLE hEvents[] = { apiData->overlapped.hEvent, apiData->m_hExitEvent }; + + while ( true ) { + KSSTREAM_HEADER packet; + memset(&packet, 0, sizeof packet); + packet.Size = sizeof(KSSTREAM_HEADER); + packet.PresentationTime.Time = 0; + packet.PresentationTime.Numerator = 1; + packet.PresentationTime.Denominator = 1; + packet.Data = &apiData->m_Buffer[0]; + packet.DataUsed = 0; + packet.FrameExtent = apiData->m_Buffer.size(); + apiData->m_pPin->ReadData(&packet, &apiData->overlapped); + + DWORD dwRet = ::WaitForMultipleObjects(2, hEvents, FALSE, INFINITE); + + if ( dwRet == WAIT_OBJECT_0 ) { + // parse packet + unsigned char* pData = (unsigned char*)packet.Data; + unsigned int iOffset = 0; + + while ( iOffset < packet.DataUsed ) { + KSMUSICFORMAT* pMusic = (KSMUSICFORMAT*)&pData[iOffset]; + iOffset += sizeof(KSMUSICFORMAT); + + MidiInApi::MidiMessage message; + message.timeStamp = 0; + for(size_t i=0;i < pMusic->ByteCount;++i) + message.bytes.push_back(pData[iOffset+i]); + + 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 << "\nRtMidiIn: message queue limit reached!!\n\n"; + } + + iOffset += pMusic->ByteCount; + + // re-align on 32 bits + if ( iOffset % 4 != 0 ) + iOffset += (4 - iOffset % 4); + } + } + else + break; + } + return 0; +} + +MidiInWinKS :: MidiInWinKS( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit ) +{ + initialize( clientName ); +} + +void MidiInWinKS :: initialize( const std::string& clientName ) +{ + WindowsKsData* data = new WindowsKsData; + apiData_ = (void*)data; + inputData_.apiData = data; + + GUID const aguidEnumCats[] = + { + { STATIC_KSCATEGORY_AUDIO }, { STATIC_KSCATEGORY_CAPTURE } + }; + data->m_pCaptureEnum.reset(new CKsEnumFilters<CKsMidiCapFilter> ); + data->m_pCaptureEnum->EnumFilters(aguidEnumCats, 2); +} + +MidiInWinKS :: ~MidiInWinKS() +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + try { + if ( data->m_pPin ) + closePort(); + } + catch(...) { + } + + delete data; +} + +void MidiInWinKS :: openPort( unsigned int portNumber, const std::string portName ) +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + + if ( portNumber < 0 || portNumber >= data->m_pCaptureEnum->m_Filters.size() ) { + std::stringstream ost; + ost << "MidiInWinKS::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + CKsMidiCapFilter* pFilter = data->m_pCaptureEnum->m_Filters[portNumber]; + data->m_pPin = pFilter->CreateCapturePin(); + + if ( data->m_pPin == NULL ) { + std::stringstream ost; + ost << "MidiInWinKS::openPort: KS error opening port (could not create pin)"; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + data->m_pPin->SetState(KSSTATE_RUN); + + DWORD threadId; + data->m_hInputThread = ::CreateThread(NULL, 0, &midiKsInputThread, &inputData_, 0, &threadId); + if ( data->m_hInputThread == NULL ) { + std::stringstream ost; + ost << "MidiInWinKS::initialize: Could not create input thread : Windows error " << GetLastError() << std::endl;; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + connected_ = true; +} + +void MidiInWinKS :: openVirtualPort( const std::string portName ) +{ + // This function cannot be implemented for the Windows KS MIDI API. + errorString_ = "MidiInWinKS::openVirtualPort: cannot be implemented in Windows KS MIDI API!"; + RtMidi::error( RtError::WARNING, errorString_ ); +} + +unsigned int MidiInWinKS :: getPortCount() +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + return (unsigned int)data->m_pCaptureEnum->m_Filters.size(); +} + +std::string MidiInWinKS :: getPortName(unsigned int portNumber) +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + + if(portNumber < 0 || portNumber >= data->m_pCaptureEnum->m_Filters.size()) { + std::stringstream ost; + ost << "MidiInWinKS::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + CKsMidiCapFilter* pFilter = data->m_pCaptureEnum->m_Filters[portNumber]; + return pFilter->GetFriendlyName(); +} + +void MidiInWinKS :: closePort() +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + connected_ = false; + + if(data->m_hInputThread) { + ::SignalObjectAndWait(data->m_hExitEvent, data->m_hInputThread, INFINITE, FALSE); + ::CloseHandle(data->m_hInputThread); + } + + if(data->m_pPin) { + data->m_pPin->SetState(KSSTATE_PAUSE); + data->m_pPin->SetState(KSSTATE_STOP); + data->m_pPin->ClosePin(); + data->m_pPin = NULL; + } +} + +// *********************************************************************// +// API: WINDOWS Kernel Streaming +// Class Definitions: MidiOutWinKS +// *********************************************************************// + +MidiOutWinKS :: MidiOutWinKS( const std::string clientName ) : MidiOutApi() +{ + initialize( clientName ); +} + +void MidiOutWinKS :: initialize( const std::string& clientName ) +{ + WindowsKsData* data = new WindowsKsData; + + data->m_pPin = NULL; + data->m_pRenderEnum.reset(new CKsEnumFilters<CKsMidiRenFilter> ); + GUID const aguidEnumCats[] = + { + { STATIC_KSCATEGORY_AUDIO }, { STATIC_KSCATEGORY_RENDER } + }; + data->m_pRenderEnum->EnumFilters(aguidEnumCats, 2); + + apiData_ = (void*)data; +} + +MidiOutWinKS :: ~MidiOutWinKS() +{ + // Close a connection if it exists. + closePort(); + + // Cleanup. + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + delete data; +} + +void MidiOutWinKS :: openPort( unsigned int portNumber, const std::string portName ) +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + + if(portNumber < 0 || portNumber >= data->m_pRenderEnum->m_Filters.size()) { + std::stringstream ost; + ost << "MidiOutWinKS::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + CKsMidiRenFilter* pFilter = data->m_pRenderEnum->m_Filters[portNumber]; + data->m_pPin = pFilter->CreateRenderPin(); + + if(data->m_pPin == NULL) { + std::stringstream ost; + ost << "MidiOutWinKS::openPort: KS error opening port (could not create pin)"; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + data->m_pPin->SetState(KSSTATE_RUN); + connected_ = true; +} + +void MidiOutWinKS :: openVirtualPort( const std::string portName ) +{ + // This function cannot be implemented for the Windows KS MIDI API. + errorString_ = "MidiOutWinKS::openVirtualPort: cannot be implemented in Windows KS MIDI API!"; + RtMidi::error( RtError::WARNING, errorString_ ); +} + +unsigned int MidiOutWinKS :: getPortCount() +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + + return (unsigned int)data->m_pRenderEnum->m_Filters.size(); +} + +std::string MidiOutWinKS :: getPortName( unsigned int portNumber ) +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + + if ( portNumber < 0 || portNumber >= data->m_pRenderEnum->m_Filters.size() ) { + std::stringstream ost; + ost << "MidiOutWinKS::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + CKsMidiRenFilter* pFilter = data->m_pRenderEnum->m_Filters[portNumber]; + return pFilter->GetFriendlyName(); +} + +void MidiOutWinKS :: closePort() +{ + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + connected_ = false; + + if ( data->m_pPin ) { + data->m_pPin->SetState(KSSTATE_PAUSE); + data->m_pPin->SetState(KSSTATE_STOP); + data->m_pPin->ClosePin(); + data->m_pPin = NULL; + } +} + +void MidiOutWinKS :: sendMessage(std::vector<unsigned char>* pMessage) +{ + std::vector<unsigned char> const& msg = *pMessage; + WindowsKsData* data = static_cast<WindowsKsData*>(apiData_); + size_t iNumMidiBytes = msg.size(); + size_t pos = 0; + + // write header + KSMUSICFORMAT* pKsMusicFormat = reinterpret_cast<KSMUSICFORMAT*>(&data->m_Buffer[pos]); + pKsMusicFormat->TimeDeltaMs = 0; + pKsMusicFormat->ByteCount = iNumMidiBytes; + pos += sizeof(KSMUSICFORMAT); + + // write MIDI bytes + if ( pos + iNumMidiBytes > data->m_Buffer.size() ) { + std::stringstream ost; + ost << "KsMidiInput::Write: MIDI buffer too small. Required " << pos + iNumMidiBytes << " bytes, only has " << data->m_Buffer.size(); + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + if ( data->m_pPin == NULL ) { + std::stringstream ost; + ost << "MidiOutWinKS::sendMessage: port is not open"; + errorString_ = ost.str(); + RtMidi::error( RtError::WARNING, errorString_ ); + } + + memcpy(&data->m_Buffer[pos], &msg[0], iNumMidiBytes); + pos += iNumMidiBytes; + + KSSTREAM_HEADER packet; + memset(&packet, 0, sizeof packet); + packet.Size = sizeof(packet); + packet.PresentationTime.Time = 0; + packet.PresentationTime.Numerator = 1; + packet.PresentationTime.Denominator = 1; + packet.Data = const_cast<unsigned char*>(&data->m_Buffer[0]); + packet.DataUsed = ((pos+3)/4)*4; + packet.FrameExtent = data->m_Buffer.size(); + + data->m_pPin->WriteData(&packet, NULL); +} + +#endif // __WINDOWS_KS__ + //*********************************************************************// -// API: LINUX JACK +// API: UNIX JACK // // Written primarily by Alexander Svetalkin, with updates for delta // time by Gary Scavone, April 2011. // // *********************************************************************// -#if defined(__LINUX_JACK__) +#if defined(__UNIX_JACK__) // JACK header files #include <jack/jack.h> @@ -2468,22 +3396,18 @@ struct JackMidiData { jack_ringbuffer_t *buffSize; jack_ringbuffer_t *buffMessage; jack_time_t lastTime; - }; - -struct Arguments { - JackMidiData *jackData; - RtMidiIn :: RtMidiInData *rtMidiIn; + MidiInApi :: RtMidiInData *rtMidiIn; }; //*********************************************************************// // API: JACK -// Class Definitions: RtMidiIn +// Class Definitions: MidiInJack //*********************************************************************// int jackProcessIn( jack_nframes_t nframes, void *arg ) { - JackMidiData *jData = ( (Arguments *) arg )->jackData; - RtMidiIn :: RtMidiInData *rtData = ( (Arguments *) arg )->rtMidiIn; + JackMidiData *jData = (JackMidiData *) arg; + MidiInApi :: RtMidiInData *rtData = jData->rtMidiIn; jack_midi_event_t event; jack_time_t long long time; @@ -2494,7 +3418,7 @@ int jackProcessIn( jack_nframes_t nframes, void *arg ) // We have midi events in buffer int evCount = jack_midi_get_event_count( buff ); if ( evCount > 0 ) { - RtMidiIn::MidiMessage message; + MidiInApi::MidiMessage message; message.bytes.clear(); jack_midi_event_get( &event, buff, 0 ); @@ -2511,59 +3435,61 @@ int jackProcessIn( jack_nframes_t nframes, void *arg ) jData->lastTime = time; - if ( rtData->usingCallback && !rtData->continueSysex ) { - RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback; - callback( message.timeStamp, &message.bytes, rtData->userData ); - } - else { - // As long as we haven't reached our queue size limit, push the message. - if ( rtData->queue.size < rtData->queue.ringSize ) { - rtData->queue.ring[rtData->queue.back++] = message; - if ( rtData->queue.back == rtData->queue.ringSize ) - rtData->queue.back = 0; - rtData->queue.size++; + if ( !rtData->continueSysex ) { + if ( rtData->usingCallback ) { + RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback; + callback( message.timeStamp, &message.bytes, rtData->userData ); + } + else { + // As long as we haven't reached our queue size limit, push the message. + if ( rtData->queue.size < rtData->queue.ringSize ) { + rtData->queue.ring[rtData->queue.back++] = message; + if ( rtData->queue.back == rtData->queue.ringSize ) + rtData->queue.back = 0; + rtData->queue.size++; + } + else + std::cerr << "\nMidiInJack: message queue limit reached!!\n\n"; } - else - std::cerr << "\nRtMidiIn: message queue limit reached!!\n\n"; } } return 0; } -void RtMidiIn :: initialize( const std::string& clientName ) +MidiInJack :: MidiInJack( const std::string clientName, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit ) +{ + initialize( clientName ); +} + +void MidiInJack :: initialize( const std::string& clientName ) { JackMidiData *data = new JackMidiData; + apiData_ = (void *) data; // Initialize JACK client - if (( data->client = jack_client_open( clientName.c_str(), JackNullOption, NULL )) == 0) - { - errorString_ = "RtMidiOut::initialize: JACK server not running?"; - error( RtError::DRIVER_ERROR ); + if (( data->client = jack_client_open( clientName.c_str(), JackNullOption, NULL )) == 0) { + errorString_ = "MidiInJack::initialize: JACK server not running?"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); return; - } - - Arguments *arg = new Arguments; - arg->jackData = data; + } - arg->rtMidiIn = &inputData_; - jack_set_process_callback( data->client, jackProcessIn, arg ); + data->rtMidiIn = &inputData_; data->port = NULL; - jack_activate( data->client ); - apiData_ = (void *) data; + jack_set_process_callback( data->client, jackProcessIn, data ); + jack_activate( data->client ); } -RtMidiIn :: ~RtMidiIn() +MidiInJack :: ~MidiInJack() { JackMidiData *data = static_cast<JackMidiData *> (apiData_); - jack_client_close( data->client ); + closePort(); - // Delete the MIDI queue. - if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring; + jack_client_close( data->client ); } -void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) +void MidiInJack :: openPort( unsigned int portNumber, const std::string portName ) { JackMidiData *data = static_cast<JackMidiData *> (apiData_); @@ -2573,8 +3499,8 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 ); if ( data->port == NULL) { - errorString_ = "RtMidiOut::openVirtualPort: JACK error creating virtual port"; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Connecting to the output @@ -2582,7 +3508,7 @@ void RtMidiIn :: openPort( unsigned int portNumber, const std::string portName ) jack_connect( data->client, name.c_str(), jack_port_name( data->port ) ); } -void RtMidiIn :: openVirtualPort( const std::string portName ) +void MidiInJack :: openVirtualPort( const std::string portName ) { JackMidiData *data = static_cast<JackMidiData *> (apiData_); @@ -2591,19 +3517,18 @@ void RtMidiIn :: openVirtualPort( const std::string portName ) JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 ); if ( data->port == NULL ) { - errorString_ = "RtMidiOut::openVirtualPort: JACK error creating virtual port"; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } -unsigned int RtMidiIn :: getPortCount() +unsigned int MidiInJack :: getPortCount() { int count = 0; JackMidiData *data = static_cast<JackMidiData *> (apiData_); // List of available ports - const char **ports = jack_get_ports( data->client, NULL, - JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); + const char **ports = jack_get_ports( data->client, NULL, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); if ( ports == NULL ) return 0; while ( ports[count] != NULL ) @@ -2614,7 +3539,7 @@ unsigned int RtMidiIn :: getPortCount() return count; } -std::string RtMidiIn :: getPortName( unsigned int portNumber ) +std::string MidiInJack :: getPortName( unsigned int portNumber ) { JackMidiData *data = static_cast<JackMidiData *> (apiData_); std::ostringstream ost; @@ -2622,19 +3547,19 @@ std::string RtMidiIn :: getPortName( unsigned int portNumber ) // List of available ports const char **ports = jack_get_ports( data->client, NULL, - JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); + JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); // Check port validity if ( ports == NULL ) { - errorString_ = "RtMidiOut::getPortName: no ports available!"; - error( RtError::WARNING ); + errorString_ = "MidiInJack::getPortName: no ports available!"; + RtMidi::error( RtError::WARNING, errorString_ ); return retStr; } if ( ports[portNumber] == NULL ) { - ost << "RtMidiOut::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiInJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::WARNING ); + RtMidi::error( RtError::WARNING, errorString_ ); } else retStr.assign( ports[portNumber] ); @@ -2643,17 +3568,18 @@ std::string RtMidiIn :: getPortName( unsigned int portNumber ) return retStr; } -void RtMidiIn :: closePort() +void MidiInJack :: closePort() { JackMidiData *data = static_cast<JackMidiData *> (apiData_); if ( data->port == NULL ) return; jack_port_unregister( data->client, data->port ); + data->port = NULL; } //*********************************************************************// // API: JACK -// Class Definitions: RtMidiOut +// Class Definitions: MidiOutJack //*********************************************************************// // Jack process callback @@ -2679,17 +3605,21 @@ int jackProcessOut( jack_nframes_t nframes, void *arg ) return 0; } -void RtMidiOut :: initialize( const std::string& clientName ) +MidiOutJack :: MidiOutJack( const std::string clientName ) : MidiOutApi() +{ + initialize( clientName ); +} + +void MidiOutJack :: initialize( const std::string& clientName ) { JackMidiData *data = new JackMidiData; // Initialize JACK client - if (( data->client = jack_client_open( clientName.c_str(), JackNullOption, NULL )) == 0) - { - errorString_ = "RtMidiOut::initialize: JACK server not running?"; - error( RtError::DRIVER_ERROR ); + if (( data->client = jack_client_open( clientName.c_str(), JackNullOption, NULL )) == 0) { + errorString_ = "MidiOutJack::initialize: JACK server not running?"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); return; - } + } jack_set_process_callback( data->client, jackProcessOut, data ); data->buffSize = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE ); @@ -2701,17 +3631,20 @@ void RtMidiOut :: initialize( const std::string& clientName ) apiData_ = (void *) data; } -RtMidiOut :: ~RtMidiOut() +MidiOutJack :: ~MidiOutJack() { JackMidiData *data = static_cast<JackMidiData *> (apiData_); + closePort(); // Cleanup jack_client_close( data->client ); jack_ringbuffer_free( data->buffSize ); jack_ringbuffer_free( data->buffMessage ); + + delete data; } -void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName ) +void MidiOutJack :: openPort( unsigned int portNumber, const std::string portName ) { JackMidiData *data = static_cast<JackMidiData *> (apiData_); @@ -2721,8 +3654,8 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 ); if ( data->port == NULL ) { - errorString_ = "RtMidiOut::openVirtualPort: JACK error creating virtual port"; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } // Connecting to the output @@ -2730,7 +3663,7 @@ void RtMidiOut :: openPort( unsigned int portNumber, const std::string portName jack_connect( data->client, jack_port_name( data->port ), name.c_str() ); } -void RtMidiOut :: openVirtualPort( const std::string portName ) +void MidiOutJack :: openVirtualPort( const std::string portName ) { JackMidiData *data = static_cast<JackMidiData *> (apiData_); @@ -2739,12 +3672,12 @@ void RtMidiOut :: openVirtualPort( const std::string portName ) JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 ); if ( data->port == NULL ) { - errorString_ = "RtMidiOut::openVirtualPort: JACK error creating virtual port"; - error( RtError::DRIVER_ERROR ); + errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port"; + RtMidi::error( RtError::DRIVER_ERROR, errorString_ ); } } -unsigned int RtMidiOut :: getPortCount() +unsigned int MidiOutJack :: getPortCount() { int count = 0; JackMidiData *data = static_cast<JackMidiData *> (apiData_); @@ -2762,7 +3695,7 @@ unsigned int RtMidiOut :: getPortCount() return count; } -std::string RtMidiOut :: getPortName( unsigned int portNumber ) +std::string MidiOutJack :: getPortName( unsigned int portNumber ) { JackMidiData *data = static_cast<JackMidiData *> (apiData_); std::ostringstream ost; @@ -2774,15 +3707,15 @@ std::string RtMidiOut :: getPortName( unsigned int portNumber ) // Check port validity if ( ports == NULL) { - errorString_ = "RtMidiOut::getPortName: no ports available!"; - error( RtError::WARNING ); + errorString_ = "MidiOutJack::getPortName: no ports available!"; + RtMidi::error( RtError::WARNING, errorString_ ); return retStr; } if ( ports[portNumber] == NULL) { - ost << "RtMidiOut::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; + ost << "MidiOutJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; errorString_ = ost.str(); - error( RtError::WARNING ); + RtMidi::error( RtError::WARNING, errorString_ ); } else retStr.assign( ports[portNumber] ); @@ -2791,7 +3724,7 @@ std::string RtMidiOut :: getPortName( unsigned int portNumber ) return retStr; } -void RtMidiOut :: closePort() +void MidiOutJack :: closePort() { JackMidiData *data = static_cast<JackMidiData *> (apiData_); @@ -2800,7 +3733,7 @@ void RtMidiOut :: closePort() data->port = NULL; } -void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) +void MidiOutJack :: sendMessage( std::vector<unsigned char> *message ) { int nBytes = message->size(); JackMidiData *data = static_cast<JackMidiData *> (apiData_); @@ -2811,4 +3744,4 @@ void RtMidiOut :: sendMessage( std::vector<unsigned char> *message ) jack_ringbuffer_write( data->buffSize, ( char * ) &nBytes, sizeof( nBytes ) ); } -#endif // __LINUX_JACK__ +#endif // __UNIX_JACK__ |
