FREObject openInputDevice(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[])
	{
		
		int index = 0;
		FREGetObjectAsInt32(argv[0],&index);

		//printf("Native MIDI :: open input device %i\n",index);
		
		int pointer = -1;
		try {
			RtMidiIn* in = new RtMidiIn();
			in->openPort(index);
			openMidiIn.push_back(in);

			pointer = (int)in;
			printf("Open midi pointer : %i (%s), num open devices :  %i\n",pointer,in->getPortName(index).c_str(),openMidiIn.size());
			// Don't ignore sysex, timing, or active sensing messages.
			midiin->ignoreTypes( false, false, false );

		}
		catch ( RtMidiError &error ) {
			error.printMessage();
		}		
		
		FREObject result;
		FRENewObjectFromInt32(pointer,&result);
		return result;
	}
Example #2
0
bool MidiInputController::enablePort(int portNumber) {
    if(portNumber < 0)
        return false;

    try {
        MidiInputCallback *callback = new MidiInputCallback;
        RtMidiIn *rtMidiIn = new RtMidiIn;

        cout << "Enabling MIDI port " << portNumber << " (" << rtMidiIn->getPortName(portNumber) << ")\n";

        rtMidiIn->openPort(portNumber);				// Open the port
        rtMidiIn->ignoreTypes(true, true, true);	// Ignore sysex, timing, active sensing

        callback->controller = this;
        callback->midiIn = rtMidiIn;
        callback->inputNumber = portNumber;

        rtMidiIn->setCallback(MidiInputController::rtMidiStaticCallback, callback);

        activePorts_[portNumber] = callback;
    }
    catch(...) {
        return false;
    }

    return true;
}
Example #3
0
void RtMidiDriver::start(const QList<bool> &deviceStatuses){
    setInputDevicesStatus(deviceStatuses);

    if(!hasInputDevices()){
        return;
    }
    stop();

    for(int deviceIndex=0; deviceIndex < inputDevicesEnabledStatuses.size(); deviceIndex++) {
        if(deviceIndex < midiStreams.size()){
            RtMidiIn* stream = midiStreams.at(deviceIndex);
            if(stream && inputDevicesEnabledStatuses.at(deviceIndex)){//device is globally enabled?
                if(!stream->isPortOpen()){
                    try{
                        qCInfo(jtMidi) << "Starting MIDI in " << QString::fromStdString(stream->getPortName(deviceIndex));
                        stream->openPort(deviceIndex);
                    }
                    catch(RtMidiError e){
                        qCCritical(jtMidi) << "Error opening midi port " << QString::fromStdString(e.getMessage());
                    }
                }
                else{
                    qCCritical(jtMidi) << "Port " << QString::fromStdString(stream->getPortName(deviceIndex)) << " already opened!";
                }
            }
        }
    }
}
Example #4
0
t_CKBOOL MidiInManager::open( MidiIn * min, t_CKINT device_num )
{
    // see if port not already open
    if( device_num >= (t_CKINT)the_mins.capacity() || !the_mins[device_num] )
    {
        // allocate the buffer
        CBufferAdvance * cbuf = new CBufferAdvance;
        if( !cbuf->initialize( BUFFER_SIZE, sizeof(MidiMsg) ) )
        {
            if( !min->m_suppress_output )
                EM_error2( 0, "MidiIn: couldn't allocate CBuffer for port %i...", device_num );
            delete cbuf;
            return FALSE;
        }

        // allocate
        RtMidiIn * rtmin = new RtMidiIn;
        try {
            rtmin->openPort( device_num );
            rtmin->setCallback( cb_midi_input, cbuf );
        } catch( RtError & err ) {
            if( !min->m_suppress_output )
            {
                // print it
                EM_error2( 0, "MidiIn: couldn't open MIDI port %i...", device_num );
                err.getMessage();
                // const char * e = err.getMessage().c_str();
                // EM_error2( 0, "...(%s)", err.getMessage().c_str() );
            }
            delete cbuf;
            return FALSE;
        }

        // resize?
        if( device_num >= (t_CKINT)the_mins.capacity() )
        {
            t_CKINT size = the_mins.capacity() * 2;
            if( device_num >= size ) size = device_num + 1;
            the_mins.resize( size );
            the_bufs.resize( size );
        }

        // put cbuf and rtmin in vector for future generations
        the_mins[device_num] = rtmin;
        the_bufs[device_num] = cbuf;
    }

    // set min
    min->min = the_mins[device_num];
    // found
    min->m_buffer = the_bufs[device_num];
    // get an index into your (you are min here) own buffer, 
    // and a free ticket to your own workshop
    min->m_read_index = min->m_buffer->join( (Chuck_Event *)min->SELF );
    min->m_device_num = (t_CKUINT)device_num;

    // done
    return TRUE;
}
Example #5
0
bool MidiInRt::open(unsigned port)
{
    RtMidiIn *midiin = lazyInstance();
    m_midiin->closePort();
    m_errorSignaled = false;
    midiin->openPort(port, defaultPortName().toStdString());
    return !m_errorSignaled;
}
Example #6
0
int main(int argc, char** argv)
{

  if (argc != 2) {
    printf("Usage: synth file.sf2\n");
    exit(0);
  }

  LightFluidSynth *usynth;

  usynth = new LightFluidSynth();

  usynth->loadSF2(argv[1]);
//  usynth->loadSF2("tim.sf2");

  RtMidiIn *midiIn = new RtMidiIn();
  if (midiIn->getPortCount() == 0) {
    std::cout << "No MIDI ports available!\n";
  }
  midiIn->openPort(0);
  midiIn->setCallback( &midiCallback, (void *)usynth );
  midiIn->ignoreTypes( false, false, false );

//   RtAudio dac(RtAudio::LINUX_PULSE);
  RtAudio dac;
  RtAudio::StreamParameters rtParams;

  // Determine the number of devices available
  unsigned int devices = dac.getDeviceCount();
  // Scan through devices for various capabilities
  RtAudio::DeviceInfo info;
  for ( unsigned int i = 0; i < devices; i++ ) {
    info = dac.getDeviceInfo( i );
    if ( info.probed == true ) {
      std::cout << "device " << " = " << info.name;
      std::cout << ": maximum output channels = " << info.outputChannels << "\n";
    }
  }
//  rtParams.deviceId = 3;
  rtParams.deviceId = dac.getDefaultOutputDevice();
  rtParams.nChannels = 2;
  unsigned int bufferFrames = FRAME_SIZE;

  RtAudio::StreamOptions options;
  options.flags = RTAUDIO_SCHEDULE_REALTIME;

  dac.openStream( &rtParams, NULL, AUDIO_FORMAT, SAMPLE_RATE, &bufferFrames, &audioCallback, (void *)usynth, &options );
  dac.startStream();

  printf("\n\nPress Enter to stop\n\n");
  cin.get();
  dac.stopStream();

  delete(usynth);
  return 0;
}
void midiInfo()
{
    cout << "MIDI INFO port = " << portopt << endl;

    std::vector<unsigned char> message;
    double stamp;
    int nBytes;
    int i;

#ifdef MARSYAS_MIDIIO  
    RtMidiIn *midiin = NULL;  
    try {
        midiin = new RtMidiIn();
    }
    catch (RtError3 &error) {
        error.printMessage();
        exit(1);
    }


    try {
        midiin->openPort(portopt);
    }
    catch (RtError3 &error) {
        error.printMessage();
        exit(1);

    }

    // Don't ignore sysex, timing, or active sensing messages.
    midiin->ignoreTypes( false, false, false ); 


    while(1) 

    {  

        stamp = midiin->getMessage( &message );
        nBytes = message.size();
        if (nBytes >0)
        {

            for ( i=0; i<nBytes; i++ )
                std::cout << "Byte " << i << " = " << (int)message[i] << ", ";
            if ( nBytes > 0 )
                std::cout << "stamp = " << stamp << '\n';
        }

        usleep(10);

    }

#endif

}
Example #8
0
  void Cursynth::setupMidi() {
    RtMidiIn* midi_in = new RtMidiIn();
    if (midi_in->getPortCount() <= 0) {
      std::cout << "No midi devices found.\n";
    }

    // Setup MIDI callbacks for every MIDI device.
    // TODO: Have a menu for only enabling some MIDI devices.
    for (unsigned int i = 0; i < midi_in->getPortCount(); ++i) {
      RtMidiIn* device = new RtMidiIn();
      device->openPort(i);
      device->setCallback(&midiCallback, (void*)this);
      midi_ins_.push_back(device);
    }

    delete midi_in;
  }
Example #9
0
static VALUE rtMidiIn_connect(VALUE self, VALUE port)
{
	RtMidiIn *device;
	Data_Get_Struct(self, RtMidiIn, device);
	
	try {
		device->openPort(NUM2INT(port));
		device->ignoreTypes( false, false, false );
	}
	catch(RtError &error)
	{
		rb_warn("could not open port");
		return Qfalse;
	}
	
	return Qtrue;
}
Example #10
0
    /* returns 0 on failure */
    int
    start_midi(int port)
    {
        if(midi.getPortCount() < 1) {
            std::cout << "No MIDI ports available!\n";
            return 0;
        }

        try {
            midi.openPort(port);
        } catch(RtError &error) {
            return 0;
        }

        // don't ignore sysex, timing, or active sensing messages
        midi.ignoreTypes(false, false, false);

        return 1;
    }
Example #11
0
//-----------------------------------------------------------------------------
// name: main()
// desc: entry point
//-----------------------------------------------------------------------------
int main( int argc, char ** argv )
{

 RtMidiIn *midiin = new RtMidiIn();

  // Check available ports.
  unsigned int nPorts = midiin->getPortCount();
  if ( nPorts == 0 ) {
    std::cout << "No ports available!\n";
    //goto cleanup;
  }

  midiin->openPort( 0 );

  // Set our callback function.  This should be done immediately after
  // opening the port to avoid having incoming messages written to the
  // queue.
  midiin->setCallback( &mycallback );

  // Don't ignore sysex, timing, or active sensing messages.
  midiin->ignoreTypes( false, false, false );

  std::cout << "\nReading MIDI input ... press <enter> to quit.\n";
  char input;
  std::cin.get(input);


    // instantiate RtAudio object
    RtAudio audio;
    // variables
    unsigned int bufferBytes = 0;
    // frame size
    unsigned int numFrames = 512;
    
    // check for audio devices
    if( audio.getDeviceCount() < 1 )
    {
        // nopes
        cout << "no audio devices found!" << endl;
        exit( 1 );
    }
    
    // let RtAudio print messages to stderr.
    audio.showWarnings( true );
    
    // set input and output parameters
    RtAudio::StreamParameters iParams, oParams;
    iParams.deviceId = audio.getDefaultInputDevice();
    iParams.nChannels = MY_CHANNELS;
    iParams.firstChannel = 0;
    oParams.deviceId = audio.getDefaultOutputDevice();
    oParams.nChannels = MY_CHANNELS;
    oParams.firstChannel = 0;
    
    // create stream options
    RtAudio::StreamOptions options;
    
    // go for it
    try {
        // open a stream
        audio.openStream( &oParams, &iParams, MY_FORMAT, MY_SRATE, &numFrames, &callme, NULL, &options );
    }
    catch( RtError& e )
    {
        // error!
        cout << e.getMessage() << endl;
        exit( 1 );
    }
    
    // compute
    bufferBytes = numFrames * MY_CHANNELS * sizeof(SAMPLE);
    
    // test RtAudio functionality for reporting latency.
    cout << "stream latency: " << audio.getStreamLatency() << " frames" << endl;
    
    for( int i = 0; i < MY_NUMSTRINGS; i++ )
    {
        // intialize
        g_ks[i].init( MY_SRATE*2, 440, MY_SRATE );
	
    }
    
    // go for it
    try {
        // start stream
        audio.startStream();
	char input;
        std::cout << "Press any key to quit ";
	std::cin.get(input);
        
        // stop the stream.
        audio.stopStream();
    }
    catch( RtError& e )
    {
        // print error message
        cout << e.getMessage() << endl;
        goto cleanup;
    }
    
cleanup:
    // close if open
    if( audio.isStreamOpen() )
        audio.closeStream();
    delete midiin;
    
    // done
    return 0;
}
Example #12
0
value rtmidi_in_openport(value obj, value port) {
  RtMidiIn *midiin = (RtMidiIn *)(intptr_t)val_float(obj);
  midiin->openPort(val_int(port));
  return alloc_null();
}
Example #13
0
int main( int argc, char *argv[] )
{
  RtMidiIn *midiin = 0;
  std::vector<unsigned char> message;
  int nBytes, i;
  double stamp;

  // Minimal command-line check.
  if ( argc > 2 ) usage();

  // RtMidiIn constructor
  try {
    midiin = new RtMidiIn();
  }
  catch ( RtError &error ) {
    error.printMessage();
    exit( EXIT_FAILURE );
  }

  // Check available ports vs. specified.
  unsigned int port = 0;
  unsigned int nPorts = midiin->getPortCount();
  if ( argc == 2 ) port = (unsigned int) atoi( argv[1] );
  if ( port >= nPorts ) {
    delete midiin;
    std::cout << "Invalid port specifier!\n";
    usage();
  }

  try {
    midiin->openPort( port );
  }
  catch ( RtError &error ) {
    error.printMessage();
    goto cleanup;
  }

  // Don't ignore sysex, timing, or active sensing messages.
  midiin->ignoreTypes( false, false, false );

  // Install an interrupt handler function.
  done = false;
  (void) signal(SIGINT, finish);

  // Periodically check input queue.
  std::cout << "Reading MIDI from port ... quit with Ctrl-C.\n";
  while ( !done ) {
    stamp = midiin->getMessage( &message );
    nBytes = message.size();
    for ( i=0; i<nBytes; i++ )
      std::cout << "Byte " << i << " = " << (int)message[i] << ", ";
    if ( nBytes > 0 )
      std::cout << "stamp = " << stamp << std::endl;

    // Sleep for 10 milliseconds.
    SLEEP( 10 );
  }

  // Clean up
 cleanup:
  delete midiin;

  return 0;
}
Example #14
0
int main (int argc, char ** argv)
{
    
    //parse tempo 
    if (argc>2)
    {
        cerr<<"Error in arguments\n";
        printHelp();
        exit(1);
    }
    else if (argc==2) 
    {
        g_tempo = atoi(argv[1]);
        if (g_tempo<40 && g_tempo>200)
        {
            cerr<<"Tempo out of bounds!\n";
            printHelp();
            exit(1);
        }
        tempoChange();
    }
    
    // set up fluid synth stuff
    // TODO: error checking!!!!
    g_settings = new_fluid_settings(); 
    g_synth = new_fluid_synth( g_settings );
    g_metronome = new_fluid_synth( g_settings );  
    
    
    //fluid_player_t* player;
    //player = new_fluid_player(g_synth);
    //fluid_player_add(player, "backing.mid");
    //fluid_player_play(player);

    
    
    if (fluid_synth_sfload(g_synth, "piano.sf2", 1) == -1)
    {
        cerr << "Error loading sound font" << endl;
        exit(1);
    }
    
    if (fluid_synth_sfload(g_metronome, "drum.sf2", 1) == -1)
    {
        cerr << "Error loading sound font" << endl;
        exit(1);
    }
    
    
    // RtAudio config + init

    // pointer to RtAudio object
    RtMidiIn * midiin = NULL;    
	RtAudio *  audio = NULL;
    unsigned int bufferSize = 512;//g_sixteenth/100;

    // MIDI config + init
    try 
    {
        midiin = new RtMidiIn();
    }
    catch( RtError & err ) {
        err.printMessage();
       // goto cleanup;
    }
    
    // Check available ports.
    if ( midiin->getPortCount() == 0 )
    {
        std::cout << "No ports available!\n";
       // goto cleanup;
    }
    // use the first available port
    if ( midiin->getPortCount() > 2)
        midiin->openPort( 1 );
    else 
        midiin->openPort( 0 );

    // set midi callback
    midiin->setCallback( &midi_callback );

    // Don't ignore sysex, timing, or active sensing messages.
    midiin->ignoreTypes( false, false, false );

    // create the object
    try
    {
        audio = new RtAudio();
        cerr << "buffer size: " << bufferSize << endl;
    }
        catch( RtError & err ) {
        err.printMessage();
        exit(1);
    }

    if( audio->getDeviceCount() < 1 )
    {
        // nopes
        cout << "no audio devices found!" << endl;
        exit( 1 );
    }
        
    // let RtAudio print messages to stderr.
    audio->showWarnings( true );

    // set input and output parameters
    RtAudio::StreamParameters iParams, oParams;
    iParams.deviceId = audio->getDefaultInputDevice();
    iParams.nChannels = 1;
    iParams.firstChannel = 0;
    oParams.deviceId = audio->getDefaultOutputDevice();
    oParams.nChannels = 2;
    oParams.firstChannel = 0;
        
    // create stream options
    RtAudio::StreamOptions options;

    // set the callback and start stream
    try
    {
        audio->openStream( &oParams, &iParams, RTAUDIO_FLOAT32, MY_SRATE, &bufferSize, &audioCallback, NULL, &options);
        audio->startStream();
        
        // test RtAudio functionality for reporting latency.
        cout << "stream latency: " << audio->getStreamLatency() << " frames" << endl;
    }
    catch( RtError & err )
    {
        err.printMessage();
        goto cleanup;
    }

    // wait for user input
    cout << "Type CTRL+C to quit:";
    
    //initialize graphics
    gfxInit(&argc,argv);
    
    // if we get here, stop!
    try
    {
        audio->stopStream();
    }
    catch( RtError & err )
    {
        err.printMessage();
    }

    // Clean up
    cleanup:
    if(audio)
    {
        audio->closeStream();
        delete audio;
    }

    
    return 0;
}
//Pluck Karplus Strong Model Plucked.cpp outputs to DAC
void PluckLive(string deviceopt, mrs_real pos, mrs_real fre, mrs_real loz, mrs_real stret)
{



#ifdef MARSYAS_MIDIIO  
    RtMidiIn *midiin = 0;
    std::vector<unsigned char> message;
    double stamp;
    int nBytes;
    int i;

    // initialize RtMidi
    try {
        midiin = new RtMidiIn();
    }
    catch (RtError3 &error) {
        error.printMessage();
        exit(1);
    }

    // find input midi port 
    try {
        midiin->openPort(portopt);
    }
    catch (RtError3 &error) {
        error.printMessage();
        exit(1);

    }
    MarSystemManager mng;
    MarSystem* series = mng.create("Series", "series");


    // create 16 plucked Karplus-Strong strings
    MarSystem* mix  = mng.create("Fanout", "mix");
    for (mrs_natural i = 0; i < 16; i++) 
    {
        ostringstream oss;
        oss << "src" << i;
        mix->addMarSystem(mng.create("Plucked", oss.str()));  
    }

    series->addMarSystem(mix);
    series->addMarSystem(mng.create("Sum", "sum"));
    series->addMarSystem(mng.create("Gain", "gain"));
    series->addMarSystem(mng.create("AudioSink", "dest"));
    series->update();


    series->updctrl("Gain/gain/mrs_real/gain", 0.10);
    series->updctrl("AudioSink/dest/mrs_real/israte", 
					series->getctrl("Fanout/mix/Plucked/src0/mrs_real/osrate"));

    series->updctrl("AudioSink/dest/mrs_natural/bufferSize", 128); 
    series->updctrl("Fanout/mix/Plucked/src0/mrs_real/frequency",fre);
    series->updctrl("Fanout/mix/Plucked/src0/mrs_real/pluckpos",pos);
    series->updctrl("Fanout/mix/Plucked/src0/mrs_real/loss",loz);
    series->updctrl("mrs_natural/inSamples", 64);
    series->update();


    // initially only play one string 
    for (int i=1; i < 16; i++)
    {
        ostringstream oss1;
        oss1 << "Fanout/mix/Plucked/src" 
			 << i << "/mrs_real/nton";
        series->updctrl(oss1.str(), 0.0);      
    }



    mrs_natural t=0;

    int channel, type, byte2, byte3;
    int mes_count = 0;
    mrs_real freq;
    int p0byte3, p1byte3, p2byte3;


    // used to keep track of polyphony
    vector<int> voices;
    for (int i=0; i < 16; i++) 
    {
        voices.push_back(0);
    }




    while(1)
    {

        // for (int i=0; i < 4; i++)
        // {
        stamp = midiin->getMessage( &message );
        // }

        nBytes = message.size();      

        if (nBytes > 0) 
        {


            byte3 = message[2];
            byte2 = message[1];
            type = message[0];

            if (deviceopt == "Keyboard")
            {

                if (type == 144) 
                {

                    // allocate voice 
                    for (int i=0; i < 16; i++)
                    {
                        if (voices[i] == 0)
                        {
                            voices[i] = byte2;
                            break;
                        }
                    }
                    // free voice if velocity is 0 (implicit noteoff)
                    for (int i=0; i < 16; i++)
                    {
                        if ((byte3 == 0)&&(voices[i] == byte2))
                        {
                            voices[i] = 0;
                            break;
                        }
                    }	      

                    for (int i=0; i < 16; i++)
                    {

                        ostringstream oss, oss1;
                        oss << "Fanout/mix/Plucked/src" 
                            << i << "/mrs_real/frequency";

                        oss1 << "Fanout/mix/Plucked/src" 
							 << i << "/mrs_real/nton";

                        if (voices[i] != 0) 
                        {
                            freq =  220.0 * pow( 2.0,(voices[i] - 57.0) / 12.0 );

                            series->updctrl(oss1.str(), 1.0);      

                            series->updctrl(oss.str(),freq);      	       		      
                            // series->update();

                        }
                    }

                }

                if (type == 128) 
                {
                    // free voice if noteoff
                    for (int i=0; i < 16; i++)
                    {
                        if (voices[i] == byte2)
                        {

                            ostringstream oss, oss1;

                            oss1 << "Fanout/mix/Plucked/src" 
								 << i << "/mrs_real/nton";


                            series->updctrl(oss1.str(), 0.0);      
                            voices[i] = 0;
                            break;
                        }
                    }	      
                }

            }


            if (deviceopt == "KiomB") 
            {
                if (byte2 == 0)
                {
                    freq =  220.0 * pow( 2.0, (byte3 - 57.0) / 12.0 );

                    if ((byte3 > 25)&&(abs(byte3 - p0byte3) > 2))
                    {
                        series->updctrl("Fanout/mix/Plucked/src0/mrs_real/frequency",freq);      		    
                    }

                }		
                p0byte3 = byte3;
            }



            if (byte2 == 1)
            {
                freq = 220.0 * pow( 2.0, (byte3 - 60.0) / 12.0 );
                if ((byte3 > 25)&&(abs(byte3 - p1byte3) > 2))
                    series->updctrl("Fanout/mix/Plucked/src1/mrs_real/frequency",freq);      

                p1byte3 = byte3;

            }


            if (byte2 == 2)
            {
                freq = 220.0 * pow( 2.0, (byte3 - 62.0) / 12.0 );
                if ((byte3 > 25)&&(abs(byte3 - p2byte3) > 2))
                    series->updctrl("Fanout/mix/Plucked/src2/mrs_real/frequency",freq);      

                p2byte3 = byte3;

            }
        }


        series->tick();
        t++;
    }


#endif


}