Exemple #1
0
bool midibus::init_out( )
{
    /* temp return */
    int ret;

    /* create ports */
    ret = snd_seq_create_simple_port(m_seq, 
				     m_name.c_str(),
			     	     SND_SEQ_PORT_CAP_NO_EXPORT |
				     SND_SEQ_PORT_CAP_READ,
				     SND_SEQ_PORT_TYPE_MIDI_GENERIC |
				     SND_SEQ_PORT_TYPE_APPLICATION );
    m_local_addr_port = ret;

    if ( ret < 0 ){
        printf( "snd_seq_create_simple_port(write) error\n");
        return false;
    }

    /* connect to */
    ret = snd_seq_connect_to( m_seq, 
			      m_local_addr_port, 
			      m_dest_addr_client, 
			      m_dest_addr_port );
    if ( ret < 0 ){
        printf( "snd_seq_connect_to(%d:%d) error\n", m_dest_addr_client, m_dest_addr_port);
        return false;
    }

    return true;
}
Exemple #2
0
bool QMidi::initMidiOut(QString outDeviceId)
{
#if defined(Q_OS_WIN)
    midiOutOpen(&midiOutPtr,outDeviceId.toInt(),0,0,CALLBACK_NULL);
#elif defined(Q_OS_LINUX)
    int err = snd_seq_open(&midiOutPtr, "default", SND_SEQ_OPEN_OUTPUT, 0);
    if(err < 0) { return false; }
    snd_seq_set_client_name(midiOutPtr, "QtMidi");

    snd_seq_create_simple_port(midiOutPtr, "Output Port",
                               SND_SEQ_PORT_CAP_READ, SND_SEQ_PORT_TYPE_MIDI_GENERIC);

    QStringList l = outDeviceId.split(":");
    int client = l.at(0).toInt();
    int port = l.at(1).toInt();
    snd_seq_connect_to(midiOutPtr, 0, client, port);
#elif defined(Q_OS_HAIKU)
	midiOutConsumer = BMidiRoster::FindConsumer(outDeviceId.toInt());
	if(midiOutConsumer == NULL) { return false; }
	midiOutLocProd = new BMidiLocalProducer("QtMidi");
	if(!midiOutLocProd->IsValid()) { midiOutLocProd->Release(); return false; } // some error ??
	midiOutLocProd->Register();
	if(midiOutLocProd->Connect(midiOutConsumer) != B_OK) { return false; }
#endif
    myOutDeviceId = outDeviceId;
    return true;
}
void JVlibForm::connect_port() {
    if (seq && strlen(SEQ_dev)) {
        //  create_source_port
        snd_seq_port_info_t *pinfo;
        snd_seq_port_info_alloca(&pinfo);
        // the first created port is 0 anyway, but let's make sure ...
        snd_seq_port_info_set_port(pinfo, 0);
        snd_seq_port_info_set_port_specified(pinfo, 1);
        snd_seq_port_info_set_name(pinfo, "midi_player");
        snd_seq_port_info_set_capability(pinfo, 0);
        snd_seq_port_info_set_type(pinfo,
               SND_SEQ_PORT_TYPE_MIDI_GENERIC |
               SND_SEQ_PORT_TYPE_APPLICATION);
        int err = snd_seq_create_port(seq, pinfo);
        check_snd("create port", err);
	
        ports = (snd_seq_addr_t *)realloc(ports, sizeof(snd_seq_addr_t));
        err = snd_seq_parse_address(seq, &ports[0], SEQ_dev);
        if (err < 0) {
            QMessageBox::critical(this, "MIDI Player", QString("Invalid port%1\n%2") .arg(SEQ_dev) .arg(snd_strerror(err)));
            return;
        }
        err = snd_seq_connect_to(seq, 0, ports[0].client, ports[0].port);
        if (err < 0 && err!= -16)
            QMessageBox::critical(this, "MIDI Player", QString("%4 Cannot connect to port %1:%2 - %3") .arg(ports[0].client) .arg(ports[0].port) .arg(strerror(errno)) .arg(err));
    }
}   // end connect_port
Exemple #4
0
void stop_midireceiver (JackVST *jvst)
{
	int err; 
	snd_seq_event_t event;
	snd_seq_t *seq2 = create_sequencer ("jfstquit", true);
	
	jvst->midiquit = 1;
	
	snd_seq_connect_to (seq2, 0, snd_seq_client_id (jvst->seq),0);
	snd_seq_ev_clear      (&event);
	snd_seq_ev_set_direct (&event);
	snd_seq_ev_set_subs   (&event);
	snd_seq_ev_set_source (&event, 0);
	snd_seq_ev_set_controller (&event,1,0x80,50);
	
	if ((err = snd_seq_event_output (seq2, &event)) < 0) {
		fst_error ("cannot send stop event to midi thread: %s\n",
			   snd_strerror (err));
	}

	snd_seq_drain_output (seq2);
	snd_seq_close (seq2);
	pthread_join (jvst->midi_thread,NULL);
	snd_seq_close (jvst->seq);
}
Exemple #5
0
int seq_open() {
  unsigned int caps;
  if (!seq_opened) {
    /* sequencer opening */
    if (snd_seq_open(&seq_handle, "hw", SND_SEQ_OPEN_OUTPUT, 0)) {
      fprintf(stderr, "Error opening ALSA sequencer.\n");
      return(-1);
    }
    /* our client id */
    my_client = snd_seq_client_id(seq_handle);
    /* set client info */
    snd_seq_set_client_name(seq_handle, DEFAULT_NAME);
    /* create port */
    caps = SND_SEQ_PORT_CAP_READ;
    if (seq_client == SND_SEQ_ADDRESS_SUBSCRIBERS)
      caps |= SND_SEQ_PORT_CAP_SUBS_READ;
    my_port = snd_seq_create_simple_port(seq_handle, DEFAULT_NAME, caps,SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
    if (my_port < 0) {
      fprintf(stderr, "can't create port\n");
      snd_seq_close(seq_handle);
      return 0;
    }
    /* subscribe to MIDI port */
    if (seq_client != SND_SEQ_ADDRESS_SUBSCRIBERS) {
      if (snd_seq_connect_to(seq_handle, my_port, seq_client, seq_port) < 0) {
        fprintf(stderr, "can't subscribe to MIDI port (%d:%d)\n", seq_client, seq_port);
        snd_seq_close(seq_handle);
        return 0;
      }
    }
  }
  seq_opened = 1;
  return 1;
}
Exemple #6
0
int ALSAMidiDriver::open() {
	std::string arg;
	unsigned int caps;

	if (isOpen)
		return -1;

	arg = getConfigSetting("alsa_port", ALSA_PORT);

	if (parse_addr(arg, &seq_client, &seq_port) < 0) {
		perr << "ALSAMidiDriver: Invalid port: " << arg << std::endl;
		return -1;
	}
	
	if (my_snd_seq_open(&seq_handle)) {
		perr << "ALSAMidiDriver: Can't open sequencer" << std::endl;
		return -1;
	}

	isOpen = true;
	
	my_client = snd_seq_client_id(seq_handle);
	snd_seq_set_client_name(seq_handle, "PENTAGRAM");
	snd_seq_set_client_group(seq_handle, "input");
	
	caps = SND_SEQ_PORT_CAP_READ;
	if (seq_client == SND_SEQ_ADDRESS_SUBSCRIBERS)
		caps = ~SND_SEQ_PORT_CAP_SUBS_READ;
	my_port =
		snd_seq_create_simple_port(seq_handle, "PENTAGRAM", caps,
								   SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
	if (my_port < 0) {
		snd_seq_close(seq_handle);
		isOpen = false;
		perr << "ALSAMidiDriver: Can't create port" << std::endl;
		return -1;
	}

	if (seq_client != SND_SEQ_ADDRESS_SUBSCRIBERS) {
		/* subscribe to MIDI port */
		if (snd_seq_connect_to(seq_handle, my_port, seq_client, seq_port) < 0) {
			snd_seq_close(seq_handle);
			isOpen = false;
			perr << "ALSAMidiDriver: "
				 << "Can't subscribe to MIDI port (" << seq_client
				 << ":" << seq_port << ")" << std::endl;
			return -1;
		}
	}

	pout << "ALSA client initialised [" << seq_client << ":"
		 << seq_port << "]" << std::endl;

	return 0;
}
Exemple #7
0
static PyObject *
alsaseq_connectto(PyObject *self, PyObject *args)
{
  int myport, dest_client, dest_port;
        
	if (!PyArg_ParseTuple(args, "iii", &myport, &dest_client, &dest_port ))
		return NULL;
        snd_seq_connect_to( seq_handle, myport, dest_client, dest_port);

	Py_INCREF(Py_None);
	return Py_None;
}
Exemple #8
0
int bx_sound_linux_c::alsa_seq_open(const char *alsadev)
{
  char *mididev, *ptr;
  int client, port, ret = 0;
  int length = strlen(alsadev) + 1;

  mididev = new char[length];

  if (mididev == NULL)
    return BX_SOUNDLOW_ERR;

  strcpy(mididev, alsadev);
  ptr = strtok(mididev, ":");
  if (ptr == NULL) {
    BX_ERROR(("ALSA sequencer setup: missing client parameters"));
    return BX_SOUNDLOW_ERR;
  }
  client = atoi(ptr);
  ptr = strtok(NULL, ":");
  if (ptr == NULL) {
    BX_ERROR(("ALSA sequencer setup: missing port parameter"));
    return BX_SOUNDLOW_ERR;
  }
  port = atoi(ptr);

  delete(mididev);

  if (snd_seq_open(&alsa_seq.handle, "default", SND_SEQ_OPEN_OUTPUT, 0) < 0) {
    BX_ERROR(("Couldn't open ALSA sequencer for midi output"));
    return BX_SOUNDLOW_ERR;
  }
  ret = snd_seq_create_simple_port(alsa_seq.handle, NULL,
    SND_SEQ_PORT_CAP_WRITE |
    SND_SEQ_PORT_CAP_SUBS_WRITE |
    SND_SEQ_PORT_CAP_READ,
    SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  if (ret < 0) {
    BX_ERROR(("ALSA sequencer: error creating port %s", snd_strerror(errno)));
  } else {
    alsa_seq.source_port = ret;
    ret = snd_seq_connect_to(alsa_seq.handle, alsa_seq.source_port, client, port);
    if (ret < 0) {
      BX_ERROR(("ALSA sequencer: could not connect to port %d:%d", client, port));
    }
  }
  if (ret < 0) {
    snd_seq_close(alsa_seq.handle);
    return BX_SOUNDLOW_ERR;
  } else {
    return BX_SOUNDLOW_OK;
  }
}
int ALSADrv_MIDI_Init(midifuncs *funcs)
{
    int result;
    
    ALSADrv_MIDI_Shutdown();
    memset(funcs, 0, sizeof(midifuncs));

    result = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0);
    if (result < 0) {
        fprintf(stderr, "ALSA snd_seq_open err %d\n", result);
        ErrorCode = ALSAErr_SeqOpen;
        return ALSAErr_Error;
    }
    
    seq_port = snd_seq_create_simple_port(seq, "output",
                  SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_WRITE,
                  SND_SEQ_PORT_TYPE_APPLICATION);
    if (seq_port < 0) {
        ALSADrv_MIDI_Shutdown();
        fprintf(stderr, "ALSA snd_seq_create_simple_port err %d\n", seq_port);
        ErrorCode = ALSAErr_CreateSimplePort;
        return ALSAErr_Error;
    }
    
    snd_seq_set_client_name(seq, "JFAudioLib application");

    seq_queue = snd_seq_alloc_queue(seq);
    if (seq_queue < 0) {
        ALSADrv_MIDI_Shutdown();
        fprintf(stderr, "ALSA snd_seq_alloc_queue err %d\n", seq_queue);
        ErrorCode = ALSAErr_AllocQueue;
        return ALSAErr_Error;
    }
    
    result = snd_seq_connect_to(seq, seq_port, 128, 0);
    if (result < 0) {
        ALSADrv_MIDI_Shutdown();
        fprintf(stderr, "ALSA snd_seq_connect_to err %d\n", result);
        ErrorCode = ALSAErr_ConnectTo;
        return ALSAErr_Error;
    }
    
    funcs->NoteOff = Func_NoteOff;
    funcs->NoteOn  = Func_NoteOn;
    funcs->PolyAftertouch = Func_PolyAftertouch;
    funcs->ControlChange = Func_ControlChange;
    funcs->ProgramChange = Func_ProgramChange;
    funcs->ChannelAftertouch = Func_ChannelAftertouch;
    funcs->PitchBend = Func_PitchBend;
    
    return ALSAErr_Ok;
}
Exemple #10
0
static void
midi_connect_sequencer() {
  int err;
  err = snd_seq_open(&midi_sequencer, "default", SND_SEQ_OPEN_OUTPUT, 0);
  assert (err >= 0);
  snd_seq_set_client_name(midi_sequencer, "midimatch");

  snd_seq_create_simple_port(midi_sequencer, "matched midi data",
							 SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
							 SND_SEQ_PORT_TYPE_MIDI_GENERIC);

  snd_seq_connect_to(midi_sequencer, 0, 128, 0);
}
Exemple #11
0
static PyObject *
alsaseq_connectto(PyObject *self, PyObject *args)
{
  int myport, dest_client, dest_port;
        
	if (!PyArg_ParseTuple(args, "iii", &myport, &dest_client, &dest_port ))
		return NULL;

        if (!seq_handle) {
                PyErr_SetString(PyExc_RuntimeError, "Must initialize module with alsaseq.client() before using it");
                return NULL;
        }

        snd_seq_connect_to( seq_handle, myport, dest_client, dest_port);

	Py_INCREF(Py_None);
	return Py_None;
}
Exemple #12
0
rimshot_alsa_output_t *
rimshot_alsa_output_open (const char *name, int client, int port)
{
    snd_seq_t *seq;
    rimshot_alsa_output_t *alsa;

    if (snd_seq_open (&seq, "default", SND_SEQ_OPEN_OUTPUT, 0) < 0) {
        return NULL;
    }

    snd_seq_set_client_name (seq, "drumkit");

    alsa = (rimshot_alsa_output_t *)calloc (1, sizeof (rimshot_alsa_output_t));
    alsa->seq = seq;
    alsa->port = snd_seq_create_simple_port (seq, "drumkit output",
                 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ,
                 SND_SEQ_PORT_TYPE_APPLICATION);

    snd_seq_connect_to (seq, alsa->port, client, port);

    return alsa;
}
int SeqContext::seq_connect_add( char *clientport )
{
	int  			ret;
	snd_seq_addr_t	*addr;
	
	addr = parseclientport( clientport );

	if( verbose ) 
		fprintf(stderr,"Adding clientport = %s; ", clientport);
		
	destlist->append( addr );

	ret = snd_seq_connect_to(handle, source.port, addr->client, addr->port);

	if( ret < 0 ) 
		fprintf(stderr,"Error connecting to client at %d:%d\n", addr->client, addr->port);
	else 
		if( verbose ) 
			fprintf(stderr,"connected to client %d:%d\n", addr->client, addr->port);
		
	return ret;
}
Exemple #14
0
static PyObject *setup(PyObject *self, PyObject *args)
{
    if (!PyArg_ParseTuple(args, "i", &dest_client_id))
        return NULL;

    // open client
    err = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0);
    if (err < 0)
        RAISE("couldnt open sequencer connection\n");

    // get client id
    my_client_id = snd_seq_client_id(seq);

    // create readable port for sending events
    readable_port = snd_seq_create_simple_port(
                                               seq, "my readable port",
                                               SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ,
                                               SND_SEQ_PORT_TYPE_MIDI_GENERIC);

    // create writable port for receiving events
    writable_port = snd_seq_create_simple_port(
                                               seq, "my writable port",
                                               SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE,
                                               SND_SEQ_PORT_TYPE_MIDI_GENERIC);

    // make subscription for sending events to device
    if (snd_seq_connect_to(seq, readable_port, dest_client_id, 0) < 0)
        RAISE("Unable to subscribe to MIDI port for writing.\n");

    // make subscription for capturing events from midi device
    if (snd_seq_connect_from(seq, writable_port, dest_client_id, 0) < 0)
        RAISE("Unable to subscribe to MIDI port for reading.\n");

    Py_INCREF(Py_None);
    return Py_None;
}
Exemple #15
0
static void stop_midireceiver(struct Data *data){
  int err; 
  snd_seq_event_t event;

  snd_seq_t *seq2=create_alsa_seq("alsagakkquit",true);

  data->toquit=true;
  snd_seq_connect_to(seq2,0,snd_seq_client_id(data->seq),0);
  snd_seq_ev_clear      (&event);
  snd_seq_ev_set_direct (&event);
  snd_seq_ev_set_subs   (&event);
  snd_seq_ev_set_source (&event, 0);
  snd_seq_ev_set_controller (&event,1,0x80,50);

  err = snd_seq_event_output (seq2, &event);
  if (err < 0){
    fprintf (stderr, "jackvst: %s: error sending midi event: %s\n",
	     __FUNCTION__, snd_strerror (err));
  }
  snd_seq_drain_output (seq2);
  snd_seq_close(seq2);
  pthread_join(data->midithread,NULL);
  snd_seq_close(data->seq);
}
Exemple #16
0
// A lot easier:
void subscribe_output(snd_seq_t *seq, int client, int port)
{
    snd_seq_connect_to(seq, 9, client, port);
}
Exemple #17
0
static
port_t* port_create(alsa_seqmidi_t *self, int type, snd_seq_addr_t addr, const snd_seq_port_info_t *info)
{
	snd_seq_client_info_t* client_info;
	port_t *port;
	char *c;
	int err;
	int jack_caps;
        char name[128];

	port = calloc(1, sizeof(port_t));
	if (!port)
		return NULL;

	port->remote = addr;

	snd_seq_client_info_alloca (&client_info);
	snd_seq_get_any_client_info (self->seq, addr.client, client_info);

	snprintf(port->name, sizeof(port->name), "alsa_pcm:%s/midi_%s_%d",
		 snd_seq_client_info_get_name(client_info), port_type[type].name, addr.port+1);

	// replace all offending characters by -
	for (c = port->name; *c; ++c)
		if (!isalnum(*c) && *c != '/' && *c != '_' && *c != ':' && *c != '(' && *c != ')')
			*c = '-';

	jack_caps = port_type[type].jack_caps;

	/* mark anything that looks like a hardware port as physical&terminal */

	if (snd_seq_port_info_get_type (info) & (SND_SEQ_PORT_TYPE_HARDWARE|SND_SEQ_PORT_TYPE_PORT|SND_SEQ_PORT_TYPE_SPECIFIC)) {
		jack_caps |= (JackPortIsPhysical | JackPortIsTerminal);
	}

	if (jack_caps & JackPortIsOutput)
		snprintf(name, sizeof(name), "system:midi_capture_%d", ++self->midi_in_cnt);
	else
		snprintf(name, sizeof(name), "system:midi_playback_%d", ++self->midi_out_cnt);

	port->jack_port = jack_port_register(self->jack,
		name, JACK_DEFAULT_MIDI_TYPE, jack_caps, 0);
	if (!port->jack_port)
		goto failed;

	jack_port_set_alias (port->jack_port, port->name);

	/* generate an alias */

	snprintf(port->name, sizeof(port->name), "%s:midi/%s_%d",
		 snd_seq_client_info_get_name (client_info), port_type[type].name, addr.port+1);

	// replace all offending characters by -
	for (c = port->name; *c; ++c)
		if (!isalnum(*c) && *c != '/' && *c != '_' && *c != ':' && *c != '(' && *c != ')')
			*c = '-';

	jack_port_set_alias (port->jack_port, port->name);

	if (type == PORT_INPUT)
		err = alsa_connect_from(self, port->remote.client, port->remote.port);
	else
		err = snd_seq_connect_to(self->seq, self->port_id, port->remote.client, port->remote.port);
	if (err)
		goto failed;

	port->early_events = jack_ringbuffer_create(MAX_EVENT_SIZE*16);

	info_log("port created: %s", port->name);
	return port;

 failed:
 	port_free(self, port);
	return NULL;
}
Exemple #18
0
/** main 
 *
 */
int
main ( int argc, char **argv )
{
	int keys = 0;
	int mc_offset = 0;

	snd_seq_event_t ev;

	int patch = 0;
	int bank = 0;

	fprintf( stderr, "lsmi-keyhack" " v" VERSION "\n" );

	get_args( argc, argv );

	fprintf( stderr, "Registering MIDI port...\n" );

	seq = open_client( CLIENT_NAME );

	if ( NULL == seq )
	{
		fprintf( stderr, "Error opening alsa sequencer!\n" );
		exit( 1 );
	}

	if ( ( port = open_output_port( seq ) ) < 0 )
	{
		fprintf( stderr, "Error opening MIDI output port!\n" );
		exit( 1 );
	}

	if ( sub_name )
	{
		snd_seq_addr_t addr;

		if ( snd_seq_parse_address( seq, &addr, sub_name ) < 0 )
			fprintf( stderr, "Couldn't parse address '%s'", sub_name );
		else if ( snd_seq_connect_to( seq, port, addr.client, addr.port ) <
				  0 )
		{
			fprintf( stderr, "Error creating subscription for port %i:%i",
					 addr.client, addr.port );
			exit( 1 );
		}
	}

	fprintf( stderr, "Initializing keyboard...\n" );

	if ( -1 == ( fd = open( device, O_RDWR ) ) )
	{
		fprintf( stderr, "Error opening event interface! (%s)\n",
				 strerror( errno ) );
		exit( 1 );
	}

	init_keyboard();

	set_traps();

	update_leds();

	fprintf( stderr, "Opening database...\n" );

	if ( database == defaultdatabase )
	{
		char *home = getenv( "HOME" );

		database = malloc( strlen( home ) + strlen( defaultdatabase ) + 2 );

		sprintf( database, "%s/%s", home, defaultdatabase );
	}

	if ( -1 == open_database( database ) )
	{
		fprintf( stderr, "******Key database missing or invalid******\n"
				 "Entering learning mode...\n"
				 "Make sure your \"keyboard\" device is connected!\n" );

		learn_mode();
	}

	analyze_map( &keys, &mc_offset );

	octave_min = ( mc_offset / 12 ) + 1;
	octave_max = 9 - ( ( keys - mc_offset ) / 12 );

	fprintf( stderr,
			 "%i keys, middle C is %ith from the left, lowest MIDI octave == %i, highest, %i\n",
			 keys, mc_offset + 1, octave_min, octave_max );

	fprintf( stderr, "Waiting for events...\n" );

	for ( ;; )
	{
		int keyi, newstate;

		keyi = get_keypress( &newstate );

		snd_seq_ev_clear( &ev );

		if ( map[keyi].control )
		{
			snd_seq_event_t e;

			if ( newstate == UP )
				continue;

			switch ( map[keyi].control )
			{
					/* All notes off */
					snd_seq_ev_set_controller( &ev, channel, 123, 0 );
					send_event( &ev );
					snd_seq_ev_clear( &ev );

				case CKEY_EXIT:
					fprintf( stderr, "Exiting...\n" );

					if ( close_database( database ) < 0 )
						fprintf( stderr, "Error saving database!\n" );

					clean_up();

					exit( 0 );

				case CKEY_MODE:

					prog_mode =
						prog_mode + 1 >
						NUM_PROG_MODES - 1 ? 0 : prog_mode + 1;
					fprintf( stderr, "Input mode change to %s\n",
							 mode_names[prog_mode] );

					update_leds();

					break;

				case CKEY_OCTAVE_DOWN:
					octave = min( octave - 1, octave_min );
					break;
				case CKEY_OCTAVE_UP:
					octave = max( octave + 1, octave_max );
					break;
				case CKEY_CHANNEL_DOWN:
					channel = min( channel - 1, 0 );
					break;
				case CKEY_CHANNEL_UP:
					channel = max( channel + 1, 15 );
					break;
				case CKEY_PATCH_DOWN:
					if ( patch == 0 && bank > 0 )
					{
						bank = min( bank - 1, 0 );
						patch = 127;

						snd_seq_ev_set_controller( &e, channel, 0, bank );
						send_event( &e );
					}
					else
						patch = min( patch - 1, 0 );

					snd_seq_ev_set_pgmchange( &ev, channel, patch );
					break;
				case CKEY_PATCH_UP:
					if ( patch == 127 && bank < 127 )
					{
						bank = max( bank + 1, 127 );
						patch = 0;

						snd_seq_ev_set_controller( &e, channel, 0, bank );
						send_event( &e );
					}
					else
						patch = max( patch + 1, 127 );

					snd_seq_ev_set_pgmchange( &ev, channel, patch );
					break;

				case CKEY_NUMERIC:
				{
					struct timeval tv;

					gettimeofday( &tv, NULL );
					/* Timeout in 5 secs */

					if ( tv.tv_sec - timeout.tv_sec >= 5 )
					{
						prog_index = 0;
					}

					timeout = tv;

					if ( prog_index == 0 )
						printf( "INPUT %s #: ", mode_names[prog_mode] );
				}

					prog_buf[prog_index++] = 48 + map[keyi].number;
					printf( "%i", map[keyi].number );
					fflush( stdout );

					if ( prog_index == 2 && prog_mode == CHANNEL )
					{

						/* FIXME: all notes off->channel */

						prog_buf[++prog_index] = '\0';
						channel = atoi( prog_buf );

						channel = max( channel, 15 );

						prog_index = 0;

						printf( " ENTER\n" );
					}
					else if ( prog_index == 3 )
					{
						prog_buf[++prog_index] = '\0';

						switch ( prog_mode )
						{
							case PATCH:
								patch = atoi( prog_buf );

								patch = max( patch, 127 );

								snd_seq_ev_set_pgmchange( &ev, channel,
														  patch );

								break;
							case BANK:
								bank = atoi( prog_buf );

								bank = max( bank, 127 );

								snd_seq_ev_set_controller( &ev, channel, 0,
														   bank );
								break;
							default:
								fprintf( stderr, "Internal error!\n" );
						}

						prog_index = 0;
						printf( " ENTER\n" );
					}

					break;
				default:
					fprintf( stderr, "Internal error!\n" );
			}

			send_event( &ev );

			continue;
		}
		else
			switch ( map[keyi].ev_type )
			{
				case SND_SEQ_EVENT_CONTROLLER:

					snd_seq_ev_set_controller( &ev, channel,
											   map[keyi].number,
											   newstate == DOWN ? 127 : 0 );

					break;

				case SND_SEQ_EVENT_NOTE:

					if ( newstate == DOWN )
						snd_seq_ev_set_noteon( &ev, channel,
											   map[keyi].number +
											   ( 12 * octave ), 64 );
					else
						snd_seq_ev_set_noteoff( &ev, channel,
												map[keyi].number +
												( 12 * octave ), 64 );
					break;

				default:
					fprintf( stderr, "Key has invalid mapping!\n" );
					break;
			}

		send_event( &ev );
	}
}
Exemple #19
0
/**************************************************************************
 * 			modOpen					[internal]
 */
static DWORD modOpen(WORD wDevID, LPMIDIOPENDESC lpDesc, DWORD dwFlags)
{
    TRACE("(%04X, %p, %08lX);\n", wDevID, lpDesc, dwFlags);
    if (lpDesc == NULL) {
	WARN("Invalid Parameter !\n");
	return MMSYSERR_INVALPARAM;
    }
    if (wDevID >= MODM_NumDevs) {
	TRACE("MAX_MIDIOUTDRV reached !\n");
	return MMSYSERR_BADDEVICEID;
    }
    if (MidiOutDev[wDevID].midiDesc.hMidi != 0) {
	WARN("device already open !\n");
	return MMSYSERR_ALLOCATED;
    }
    if (!MidiOutDev[wDevID].bEnabled) {
	WARN("device disabled !\n");
	return MIDIERR_NODEVICE;
    }
    if ((dwFlags & ~CALLBACK_TYPEMASK) != 0) {
	WARN("bad dwFlags\n");
	return MMSYSERR_INVALFLAG;
    }
    if (!MidiOutDev[wDevID].bEnabled) {
	TRACE("disabled wDevID\n");
	return MMSYSERR_NOTENABLED;
    }

    MidiOutDev[wDevID].lpExtra = 0;

    switch (MidiOutDev[wDevID].caps.wTechnology) {
    case MOD_FMSYNTH:
    case MOD_MIDIPORT:
    case MOD_SYNTH:
	if (midiOpenSeq(1) < 0) {
	    return MMSYSERR_ALLOCATED;
	}
	break;
    default:
	WARN("Technology not supported (yet) %d !\n",
	     MidiOutDev[wDevID].caps.wTechnology);
	return MMSYSERR_NOTENABLED;
    }

    MidiOutDev[wDevID].wFlags = HIWORD(dwFlags & CALLBACK_TYPEMASK);

    MidiOutDev[wDevID].lpQueueHdr = NULL;
    MidiOutDev[wDevID].dwTotalPlayed = 0;
    MidiOutDev[wDevID].bufsize = 0x3FFF;
    MidiOutDev[wDevID].midiDesc = *lpDesc;

    /* Connect our app port to the device port */
    if (snd_seq_connect_to(midiSeq, port_out, MidiOutDev[wDevID].addr.client, MidiOutDev[wDevID].addr.port) < 0)
	return MMSYSERR_NOTENABLED;
    
    if (MIDI_NotifyClient(wDevID, MOM_OPEN, 0L, 0L) != MMSYSERR_NOERROR) {
	WARN("can't notify client !\n");
	return MMSYSERR_INVALPARAM;
    }
    TRACE("Successful !\n");
    return MMSYSERR_NOERROR;
}
int main(int argc, char **argv)
{
	int i;
	int listen_port = -1;
	char *client_name = "net2alsamidi";
	char *connect_client = NULL;
	int connect_port = -1;

	for (i = 1; i < argc; i++)
	{
		if (strcmp(argv[i], "--port") == 0)
		{
			if (++i == argc) usage(argv[0]);
			listen_port = atoi(argv[i]);
		}
		else if (strcmp(argv[i], "--name") == 0)
		{
			if (++i == argc) usage(argv[0]);
			client_name = argv[i];
		}
		else if (strcmp(argv[i], "--connect") == 0)
		{
			if (++i == argc) usage(argv[0]);
			connect_client = argv[i];
			if (++i == argc) usage(argv[0]);
			connect_port = atoi(argv[i]);
		}
		else
		{
			usage(argv[0]);
		}
	}

	if (listen_port > 0)
	{
		snd_seq_t *seq;
		int port;

		if (snd_seq_open(&seq, "default", SND_SEQ_OPEN_OUTPUT, 0) < 0)
		{
			fprintf(stderr, "Cannot open the ALSA sequencer.\n");
			exit(1);
		}

		snd_seq_set_client_name(seq, client_name);
		port = snd_seq_create_simple_port(seq, "from NetMIDI client", SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);

		if ((connect_client != NULL) && (connect_port >= 0))
		{
			int connect_client_id = -1;

			{
				snd_seq_client_info_t *client_info;
				snd_seq_client_info_malloc(&client_info);

				while (snd_seq_query_next_client(seq, client_info) == 0)
				{
					if (strcmp(snd_seq_client_info_get_name(client_info), connect_client) == 0)
					{
						connect_client_id = snd_seq_client_info_get_client(client_info);
						break;
					}
				}

				snd_seq_client_info_free(client_info);
			}

			if (connect_client_id < 0) connect_client_id = atoi(connect_client);
			snd_seq_connect_to(seq, port, connect_client_id, connect_port);
		}

		{
			int server_socket;
			struct sockaddr_in server_address;

			if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
			{
				fprintf(stderr, "Cannot start a NetMIDI server on port %d.\n", listen_port);
				exit(1);
			}

			server_address.sin_family = AF_INET;
			server_address.sin_port = htons(listen_port);
			server_address.sin_addr.s_addr = INADDR_ANY;

			if (bind(server_socket, (struct sockaddr *)(&server_address), sizeof(server_address)) < 0)
			{
				fprintf(stderr, "Cannot start a NetMIDI server on port %d.\n", listen_port);
				exit(1);
			}

			if (listen(server_socket, 1) < 0)
			{
				fprintf(stderr, "Cannot start a NetMIDI server on port %d.\n", listen_port);
				exit(1);
			}

			while (1)
			{
				int socket_to_client;

				if ((socket_to_client = accept(server_socket, NULL, NULL)) >= 0)
				{
					snd_midi_event_t *midi_event_parser;
					snd_seq_event_t *event;
					unsigned char buffer[BUFFER_SIZE];
					int bytes_read;

					{
						char one = 1;
						setsockopt(socket_to_client, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
					}

					snd_midi_event_new(BUFFER_SIZE, &midi_event_parser);

					while ((bytes_read = recv(socket_to_client, buffer, BUFFER_SIZE, 0)) > 0)
					{
						for (i = 0; i < bytes_read; i++)
						{
							if (snd_midi_event_encode_byte(midi_event_parser, buffer[i], event) == 1)
							{
								snd_seq_event_output_direct(seq, event);
							}
						}
					}

					snd_midi_event_free(midi_event_parser);
					close(socket_to_client);
				}
			}

			close(server_socket);
		}

		snd_seq_delete_simple_port(seq, port);
		snd_seq_close(seq);
	}
	else
	{
		usage(argv[0]);
	}

	return 0;
}
Exemple #21
0
int MidiDriver_ALSA::open() {
	if (_isOpen)
		return MERR_ALREADY_OPEN;
	_isOpen = true;

	if (my_snd_seq_open(&seq_handle) < 0) {
		error("Can't open sequencer");
		return -1;
	}

	my_client = snd_seq_client_id(seq_handle);
	if (snd_seq_set_client_name(seq_handle, "RESIDUALVM") < 0) {
		error("Can't set sequencer client name");
	}
	snd_seq_set_client_group(seq_handle, "input");

	// According to http://www.alsa-project.org/~tiwai/alsa-subs.html
	// you can set read or write capabilities to allow other clients to
	// read or write the port. I don't think we need that, unless maybe
	// to be able to record the sound, but I can't get that to work even
	// with those capabilities.

	my_port = snd_seq_create_simple_port(seq_handle, "RESIDUALVM port 0", 0,
	                                     SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);

	if (my_port < 0) {
		snd_seq_close(seq_handle);
		error("Can't create port");
		return -1;
	}

	if (seq_client != SND_SEQ_ADDRESS_SUBSCRIBERS) {
		// Subscribe to MIDI port. Prefer one that doesn't already have
		// any connections, unless we've forced a port number already.
		if (seq_port == -1) {
			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_get_any_client_info(seq_handle, seq_client, cinfo);

			int first_port = -1;
			int found_port = -1;

			snd_seq_port_info_set_client(pinfo, seq_client);
			snd_seq_port_info_set_port(pinfo, -1);
			while (found_port == -1 && snd_seq_query_next_port(seq_handle, pinfo) >= 0) {
				if (check_permission(pinfo)) {
					if (first_port == -1)
						first_port = snd_seq_port_info_get_port(pinfo);
					if (found_port == -1 && snd_seq_port_info_get_write_use(pinfo) == 0)
						found_port = snd_seq_port_info_get_port(pinfo);
				}
			}

			if (found_port == -1) {
				// Should we abort here? For now, use the first
				// available port.
				seq_port = first_port;
				warning("MidiDriver_ALSA: All ports on client %d (%s) are already in use", seq_client, snd_seq_client_info_get_name(cinfo));
			} else {
				seq_port = found_port;
			}
		}

		if (snd_seq_connect_to(seq_handle, my_port, seq_client, seq_port) < 0) {
			error("Can't subscribe to MIDI port (%d:%d) see README for help", seq_client, seq_port);
		}
	}

	printf("Connected to Alsa sequencer client [%d:%d]\n", seq_client, seq_port);
	printf("ALSA client initialized [%d:0]\n", my_client);

	return 0;
}
Exemple #22
0
struct a2j_port *
a2j_port_create (alsa_midi_driver_t * driver, int dir, snd_seq_addr_t addr, const snd_seq_port_info_t * info)
{
	struct a2j_port *port;
	int err;
	int client;
	snd_seq_client_info_t * client_info_ptr;
	int jack_caps;
	struct a2j_stream * stream_ptr;

	stream_ptr = &driver->stream[dir];

	if ((err = snd_seq_client_info_malloc (&client_info_ptr)) != 0) {
		a2j_error("Failed to allocate client info");
		goto fail;
	}

	client = snd_seq_port_info_get_client (info);

	err = snd_seq_get_any_client_info (driver->seq, client, client_info_ptr);
	if (err != 0) {
		a2j_error("Failed to get client info");
		goto fail_free_client_info;
	}

	a2j_debug ("client name: '%s'", snd_seq_client_info_get_name(client_info_ptr));
	a2j_debug ("port name: '%s'", snd_seq_port_info_get_name(info));

	port = calloc (1, sizeof(struct a2j_port));
	if (!port) {
		goto fail_free_client_info;
	}

	port->driver_ptr = driver;
	port->jack_port = JACK_INVALID_PORT;
	port->remote = addr;

	a2j_port_fill_name (port, dir, client_info_ptr, info, false);

	/* Add port to list early, before registering to JACK, so map functionality is guaranteed to work during port registration */
	list_add_tail (&port->siblings, &stream_ptr->list);
	
	if (dir == A2J_PORT_CAPTURE) {
		jack_caps = JackPortIsOutput;
	} else {
		jack_caps = JackPortIsInput;
	}

	/* mark anything that looks like a hardware port as physical&terminal */
	if (snd_seq_port_info_get_type (info) & (SND_SEQ_PORT_TYPE_HARDWARE|SND_SEQ_PORT_TYPE_PORT|SND_SEQ_PORT_TYPE_SPECIFIC)) {
		jack_caps |= JackPortIsPhysical|JackPortIsTerminal;
	}

	port->jack_port = jack_port_register (driver->jack_client, port->name, JACK_DEFAULT_MIDI_TYPE, jack_caps, 0);
	if (port->jack_port == JACK_INVALID_PORT) {
		a2j_error("jack_port_register() failed for '%s'", port->name);
		goto fail_free_port;
	}

	if (dir == A2J_PORT_CAPTURE) {
		err = a2j_alsa_connect_from (driver, port->remote.client, port->remote.port);
	} else {
		err = snd_seq_connect_to (driver->seq, driver->port_id, port->remote.client, port->remote.port);
	}

	if (err) {
		a2j_debug("port skipped: %s", port->name);
		goto fail_free_port;
	}

	port->inbound_events = jack_ringbuffer_create(MAX_EVENT_SIZE*16);

	a2j_debug("port created: %s", port->name);
	return port;

  fail_free_port:
	list_del (&port->siblings);

	a2j_port_free (port);

  fail_free_client_info:
	snd_seq_client_info_free (client_info_ptr);

  fail:
	return NULL;
}
Exemple #23
0
/** main 
 *
 */
int
main ( int argc, char **argv )
{
	fprintf( stderr, "lsmi-joystick" " v" VERSION "\n" );

	get_args( argc, argv );

	fprintf( stderr, "Registering MIDI port...\n" );

	seq = open_client( CLIENT_NAME );

	if ( NULL == seq )
	{
		fprintf( stderr, "Error opening alsa sequencer!\n" );
		exit( 1 );
	}

	if ( ( port = open_output_port( seq ) ) < 0 )
	{
		fprintf( stderr, "Error opening MIDI output port!\n" );
		exit( 1 );
	}

	if ( sub_name )
	{
		snd_seq_addr_t addr;

		if ( snd_seq_parse_address( seq, &addr, sub_name ) < 0 )
			fprintf( stderr, "Couldn't parse address '%s'", sub_name );
		else
		if ( snd_seq_connect_to( seq, port, addr.client, addr.port ) < 0 )
		{
			fprintf( stderr, "Error creating subscription for port %i:%i", addr.client, addr.port );
			exit( 1 );
		}
	}

	if ( daemonize )
	{
		printf( "Running as daemon...\n" );
		if ( fork() )
			exit( 0 );
		else
		{
			fclose( stdout );
			fclose( stderr );
		}
	}

	fprintf( stderr, "Initializing joystick...\n" );

	if ( -1 == ( jfd = open( joydevice, O_RDONLY ) ) )
	{
		fprintf( stderr, "Error opening event interface! (%s)\n", strerror( errno ) );
		clean_up();
		exit(1);
	}

	set_traps();

	fprintf( stderr, "Waiting for events...\n" );

	for ( ;; )
	{
		struct js_event e;
		snd_seq_event_t ev;
		static int b1;
		static int b2;

		read (jfd, &e, sizeof(struct js_event));

		snd_seq_ev_clear( &ev );

		switch (e.type)
		{
			case JS_EVENT_BUTTON:
				switch (e.number)
				{
					case 0:
						if(e.value)
							b1 = 1;
						else
						{
							b1 = 0;
							snd_seq_ev_set_pitchbend( &ev, channel, 0 );

							send_event( &ev );
						}
						break;
					case 1:
						if (e.value)
							b2 = 1;
						else
						{
							b2 = 0;
							snd_seq_ev_set_controller( &ev, channel, 1, 0 );
							send_event( &ev );
							snd_seq_ev_set_controller( &ev, channel, 33, 0 );
							send_event( &ev );
						}
						break;
				}
				break;
			case JS_EVENT_AXIS:
				
				if ( e.number == 1 && ( b1 || nohold ) )
				{
					snd_seq_ev_set_pitchbend( &ev, channel, 0 - (int)((e.value) * ((float)8191/32767) ));

					send_event( &ev );
				}
				else
				if ( ( e.number == 1 && b2 ) ||
					 ( e.number == 0 && ( ( b1 && b2 ) || nohold ) )
				)
				{
					int fine = (int)((0 - e.value) + 32767) * ((float)16383/65534);
					int	course = fine >> 7;
					fine &= 0x7F;

					snd_seq_ev_set_controller( &ev, channel, 1, course );
					send_event( &ev );
					snd_seq_ev_set_controller( &ev, channel, 33, fine );
					send_event( &ev );
				}
				break;

			 default:
				break;
		}

	}
Exemple #24
0
/** main 
 *
 */
int
main ( int argc, char **argv )
{
	snd_seq_event_t ev;
	struct input_event iev;
	snd_seq_addr_t addr;

	fprintf( stderr, "lsmi-mouse" " v" VERSION "\n" );

	get_args( argc, argv );

	fprintf( stderr, "Initializing mouse interface...\n" );

	if ( -1 == ( fd = open( device, O_RDONLY ) ) )
	{
		fprintf( stderr, "Error opening event interface! (%s)\n", strerror( errno ) );
		exit(1);
	}

	init_mouse();

	fprintf( stderr, "Registering MIDI port...\n" );

	seq = open_client( CLIENT_NAME  );
	port = open_output_port( seq );

	if ( sub_name )
	{
		if ( snd_seq_parse_address( seq, &addr, sub_name ) < 0 )
			fprintf( stderr, "Couldn't parse address '%s'", sub_name );
		else
		if ( snd_seq_connect_to( seq, port, addr.client, addr.port ) < 0 )
		{
			fprintf( stderr, "Error creating subscription for port %i:%i", addr.client, addr.port );
			exit( 1 );
		}
	}
	
	if ( daemonize )
	{
		printf( "Running as daemon...\n" );
		if ( fork() )
			exit( 0 );
		else
		{
			fclose( stdout );
			fclose( stderr );
		}
	}

	set_traps();

	fprintf( stderr, "Waiting for packets...\n" );

	for ( ;; )
	{
		int i;

		read( fd, &iev, sizeof( iev ) );

		if ( iev.type != EV_KEY )
			continue;

		switch ( iev.code )
		{
			case BTN_LEFT:		i = 0; break;
			case BTN_MIDDLE:	i = 1; break;
			case BTN_RIGHT:		i = 2; break;
				break;
			default:
				continue;
				break;
		}

		snd_seq_ev_clear( &ev );

		switch ( ev.type = map[i].ev_type )
		{
			case SND_SEQ_EVENT_CONTROLLER:

				snd_seq_ev_set_controller( &ev, map[i].channel,
												map[i].number,
												iev.value == DOWN ? 127 : 0 );
				break;

			case SND_SEQ_EVENT_NOTEON:
				
				snd_seq_ev_set_noteon( &ev, map[i].channel,
											map[i].number,
											iev.value == DOWN ? 127 : 0 );
				break;

			default:
				fprintf( stderr,
						 "Internal error: invalid mapping!\n" );
				continue;
				break;
		}

		send_event( &ev );
	}
}
Exemple #25
0
int main(int argc, char *argv[]) {

  int getopt_return;
  int option_index;
  int valid;
  snd_seq_t *seq_handle;
  int out_port;
  snd_seq_addr_t seq_addr;
  snd_seq_event_t ev;
  
  valid = 0;
  while (((getopt_return = getopt_long(argc, argv, "ha:p:c:b:n:o:", options, &option_index)) >= 0) && (valid < 2)) {
    switch(getopt_return) {
      case 'a':
        valid++;
        if (snd_seq_open(&seq_handle, "hw", SND_SEQ_OPEN_DUPLEX, 0) < 0) {
          fprintf(stderr, "Error opening ALSA sequencer.\n");
          exit(1);  
        }
        snd_seq_set_client_name(seq_handle, "MidiSend");
        if ((out_port = snd_seq_create_simple_port(seq_handle, "MidiSend",
                        SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ,
                        SND_SEQ_PORT_TYPE_APPLICATION)) < 0) {
          fprintf(stderr, "Error creating sequencer port.\n");
          exit(1);
        }   
        snd_seq_parse_address(seq_handle, &seq_addr, optarg);
        snd_seq_connect_to(seq_handle, out_port, seq_addr.client, seq_addr.port);
        snd_seq_ev_clear(&ev);
        snd_seq_ev_set_subs(&ev);  
        snd_seq_ev_set_direct(&ev);
        snd_seq_ev_set_source(&ev, out_port);
        break;
      case 'p':
        if (valid) {
          valid++;
          if (argc < 6) {
            fprintf(stderr, "\nMissing parameter(s): midisend --program <ch> <prg>\n\n");
          } else {
            ev.data.control.channel = atoi(optarg);
            ev.type = SND_SEQ_EVENT_PGMCHANGE;
            ev.data.control.value = atoi(argv[optind]);
          }
        }  
        break;
      case 'c':
        if (valid) {
          valid++;
          if (argc < 7) {
            fprintf(stderr, "\nMissing parameter(s): midisend --control <ch> <ctrl> <val>\n\n");
          } else {
            ev.data.control.channel = atoi(optarg);
            ev.type = SND_SEQ_EVENT_CONTROLLER;
            ev.data.control.param = atoi(argv[optind]);
            ev.data.control.value = atoi(argv[optind + 1]);
          }   
        }  
        break;
      case 'b':
        if (valid) {
          valid++;
          if (argc < 6) {
            fprintf(stderr, "\nMissing parameter(s): midisend --bend <ch> <val>\n\n");
          } else {
            ev.data.control.channel = atoi(optarg);
            ev.type = SND_SEQ_EVENT_PITCHBEND;
            ev.data.control.value = atoi(argv[optind]) - 8192;
          }
        }  
        break;
      case 'n':
        if (valid) {
          valid++;
          if (argc < 8) {
            fprintf(stderr, "\nMissing parameter(s): midisend --note <ch> <on> <num> <vel>\n\n");
          } else {
            ev.data.control.channel = atoi(optarg);
            ev.type = (atoi(argv[optind])) ? SND_SEQ_EVENT_NOTEON : SND_SEQ_EVENT_NOTEOFF;
            ev.data.note.note = atoi(argv[optind + 1]);
            ev.data.note.velocity = atoi(argv[optind + 2]);
          }  
        }  
        break;
      case 'o':
        if (valid) {
          valid++;
          if (argc < 5) {
            fprintf(stderr, "\nMissing parameter(s): midisend --off <ch>\n\n");
          } else {
            ev.data.control.channel = atoi(optarg);
            ev.type = SND_SEQ_EVENT_CONTROLLER;
            ev.data.control.param = MIDI_CTL_ALL_NOTES_OFF;
            ev.data.control.value = 0;
          }   
        }  
        break;
      case 'h':
        valid = 3;
        printf("\nMidiSend 0.0.1\nWritten by Matthias Nagorni\n");
        printf("(c)2004 SUSE Linux AG Nuremberg\n");
        printf("Licensed under GNU General Public License\n\n");
        printf("--alsa <port>                  ALSA Sequencer Port (e.g. 64:0)\n");
        printf("--program <ch> <prg>           Program Change\n");
        printf("--control <ch> <ctrl> <val>    Control Change\n");
        printf("--bend <ch> <val>              Pitch Bend (0..16383, center = 8192)\n");
        printf("--note <ch> <on> <num> <vel>   Note On (on=1) Note Off (on=0)\n");
        printf("--off <ch>                     All Notes Off\n\n");
        exit(EXIT_SUCCESS);
    }
  }
  if (valid < 2) {
    fprintf(stderr, "\nUsage: midisend PORT COMMAND PARAMETERS\n\n");
    fprintf(stderr, "Type \'midisend -h\' for a list of valid commands.\n\n");
  } else if (valid == 2) {
    snd_seq_event_output_direct(seq_handle, &ev);
  }
}
static GstStateChangeReturn
gst_amidisrc_change_state (GstElement * element, GstStateChange transition )
{
  GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
  GstaMIDISrc *src = GST_AMIDISRC (element);

  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
		 // TODO: Open our listen alsa ports
		//     1. Open sequencer
		//     2. If we have a client and port, connect to them
		printf("***Here: %s:%d\n",__FILE__,__LINE__);

		if ((snd_seq_open(&src->a_seq, src->device, SND_SEQ_OPEN_INPUT, 0)) < 0)
			return GST_STATE_CHANGE_FAILURE;
		if( src->a_seq == NULL )
			return GST_STATE_CHANGE_FAILURE;
		snd_seq_set_client_name(src->a_seq, "gstreamer");
		if ((src->a_port = snd_seq_create_simple_port(src->a_seq, "In",
						SND_SEQ_PORT_CAP_WRITE |
						SND_SEQ_PORT_CAP_SUBS_WRITE,
						SND_SEQ_PORT_TYPE_MIDI_GENERIC)) < 0)
		{
			return GST_STATE_CHANGE_FAILURE;
		}
		src->a_queue = snd_seq_alloc_queue(src->a_seq);
		if( src->a_queue < 0 )
			return GST_STATE_CHANGE_FAILURE;
		// Only connect if we have positive client/port
		if( src->client >= 0 && src->port >= 0 )
		{
			if( snd_seq_connect_to(src->a_seq, src->a_port, src->client, src->port) < 0 )
				return GST_STATE_CHANGE_FAILURE;
		}
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
		return GST_STATE_CHANGE_NO_PREROLL;
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
  if (ret == GST_STATE_CHANGE_FAILURE)
    return ret;

  switch (transition) {
    case GST_STATE_CHANGE_READY_TO_NULL:
		 // TODO: close our listening alsa ports
		 // disconnect from midi port
		printf("***Here: %s:%d\n",__FILE__,__LINE__);
		if( src->a_queue >= 0 ){
			if( snd_seq_free_queue( src->a_seq, src->a_queue ) < 0 )
				return GST_STATE_CHANGE_FAILURE;
		}
		if( src->a_port >= 0 && src->a_seq != NULL){
			if( snd_seq_delete_simple_port(src->a_seq,src->a_port) < 0 ){
				return GST_STATE_CHANGE_FAILURE;
			}
		}
		if( snd_seq_close( src->a_seq ) < 0 )
			return GST_STATE_CHANGE_FAILURE;
      break;
	 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
		return GST_STATE_CHANGE_NO_PREROLL;
		break;
    default:
      break;
  }

  return ret;
}