Example #1
0
int
Server_pm_deinit(Server *self)
{
    int i = 0;

    PyoPmBackendData *be_data = (PyoPmBackendData *) self->midi_be_data;

    if (self->withPortMidi == 1) {
        for (i=0; i<self->midiin_count; i++) {
            Pm_Close(be_data->midiin[i]);
        }
    }
    if (self->withPortMidiOut == 1) {
        for (i=0; i<self->midiout_count; i++) {
            Pm_Close(be_data->midiout[i]);
        }
    }
    if (self->withPortMidi == 1 || self->withPortMidiOut == 1) {
        if (Pt_Started())
            Pt_Stop();
        Pm_Terminate();
    }
    self->withPortMidi = 0;
    self->withPortMidiOut = 0;
    
    free(self->midi_be_data);

    return 0;
}
Example #2
0
/*
-------------------------------------------------------------
*/
void midiCleanUp()
{
	ScopeMutexLock mulo(&gPmStreamMutex);

	if(gMIDIInitialized) {
		for (int i=0; i<gNumMIDIOutPorts; ++i) {
			Pm_Abort(gMIDIOutStreams[i]);
			Pm_Close(gMIDIOutStreams[i]);
		}
		for (int i=0; i<gNumMIDIInPorts; ++i) {
			Pm_Abort(gMIDIInStreams[i]);
			Pm_Close(gMIDIInStreams[i]);
		}

		gNumMIDIOutPorts = 0;
		gNumMIDIInPorts = 0;
	}

	// set the stream pointers to NULL
	memset(gMIDIInStreams,0,kMaxMidiPorts*sizeof(PmStream*));
	memset(gMIDIOutStreams,0,kMaxMidiPorts*sizeof(PmStream*));

	// delete the objects that map in/out indices to Pm dev indices
	gMidiInputIndexToPmDevIndex.clear();
	gMidiOutputIndexToPmDevIndex.clear();
	gMidiPmDevIndexToInputIndex.clear();
	gMidiPmDevIndexToOutputIndex.clear();

	gMIDIInitialized = false;
}
Example #3
0
void sys_close_midi( void)
{
    int i;
    for (i = 0; i < mac_nmidiindev; i++)
        Pm_Close(mac_midiindevlist[i]);
    mac_nmidiindev = 0;
    for (i = 0; i < mac_nmidioutdev; i++)
        Pm_Close(mac_midioutdevlist[i]);
    mac_nmidioutdev = 0;
}
Example #4
0
void keyboard_kill(MidiObj* m) {
	if(m->midi_stream_out) {
		Pm_Close(m->midi_stream_out);
		m->midi_stream_out = NULL;
	}
	if(m->midi_stream) {
		Pm_Close(m->midi_stream);
		m->midi_stream = NULL;
	}
	//Pm_Terminate();
}
Example #5
0
void keyboard_kill() {
	if (midi_stream) {
		Pm_Close(midi_stream);
		midi_stream = NULL;
	}
	Pm_Terminate();
}
Example #6
0
PortMidiDriver::~PortMidiDriver()
      {
      if (inputStream) {
            Pt_Stop();
            Pm_Close(inputStream);
            }
      }
Example #7
0
void osd_close_midi_channel(osd_midi_device *dev)
{
	#ifndef DISABLE_MIDI
	Pm_Close(dev->pmStream);
	osd_free(dev);
	#endif
}
Example #8
0
/*
 * Method:    Pm_Close
 */
JNIEXPORT jint JNICALL Java_jportmidi_JPortMidiApi_Pm_1Close
  (JNIEnv *env, jclass cl, jobject jstream)
{
    CLASS(c, jstream);
    ADDRESS_FID(fid, c);
    return Pm_Close(PMSTREAM(jstream, fid));
}
Example #9
0
midibus::~midibus ()
{
    if (not_nullptr(m_pms))
    {
        Pm_Close(m_pms);
        m_pms = nullptr;
    }
}
Example #10
0
/*
 * the somethingStupid parameter can be set to simulate a program crash.
 * We want PortMidi to close Midi ports automatically in the event of a
 * crash because Windows does not (and this may cause an OS crash)
 */
void main_test_input(unsigned int somethingStupid) {
    PmStream * midi;
    PmError status, length;
    PmEvent buffer[1];
    int num = 10;
    int i = get_number("Type input number: ");
    /* It is recommended to start timer before Midi; otherwise, PortMidi may
       start the timer with its (default) parameters
     */
    TIME_START;

    /* open input device */
    Pm_OpenInput(&midi, 
                 i,
                 DRIVER_INFO, 
                 INPUT_BUFFER_SIZE, 
                 TIME_PROC, 
                 TIME_INFO);

    printf("Midi Input opened. Reading %d Midi messages...\n", num);
    Pm_SetFilter(midi, PM_FILT_ACTIVE | PM_FILT_CLOCK | PM_FILT_SYSEX);
    /* empty the buffer after setting filter, just in case anything
       got through */
    while (Pm_Poll(midi)) {
        Pm_Read(midi, buffer, 1);
    }
    /* now start paying attention to messages */
    i = 0; /* count messages as they arrive */
    while (i < num) {
        status = Pm_Poll(midi);
        if (status == TRUE) {
            length = Pm_Read(midi,buffer, 1);
            if (length > 0) {
                printf("Got message %d: time %ld, %2lx %2lx %2lx\n",
                       i,
                       (long) buffer[0].timestamp,
                       (long) Pm_MessageStatus(buffer[0].message),
                       (long) Pm_MessageData1(buffer[0].message),
                       (long) Pm_MessageData2(buffer[0].message));
                i++;
            } else {
                assert(0);
            }
        }
        /* simulate crash if somethingStupid is 1 or 2 */
        if ((i > (num/2)) && (somethingStupid == 1)) {
            doSomethingStupid();
        } else if ((i > (num/2)) && (somethingStupid == 2)) {
            doSomethingReallyStupid();
        }
    }

    /* close device (this not explicitly needed in most implementations) */
    printf("ready to close...");

    Pm_Close(midi);
    printf("done closing...");
}
Example #11
0
MIDIOutput::~MIDIOutput()
{
	mRunning = NO;
    
    if (mStream) {
        Pm_Close(mStream);
        mStream = NULL;
    }
}
Example #12
0
static PyObject * MidiListener_stop(MidiListener *self) { 
    int i;
    Pt_Stop();
    for (i=0; i<self->midicount; i++) {
        Pm_Close(self->midiin[i]);
    }
    Pm_Terminate();    
    self->active = 0;
	Py_INCREF(Py_None);
	return Py_None;
};
Example #13
0
void exitFunction() {
  if (isInit) {
    printf("Terminating PortMidi\n");
    if (outStream != NULL) {
      Pm_Close(outStream);
      outStream = NULL;
    }
    Pt_Stop();
    Pm_Terminate();
    isInit = 0;
  }
}
Example #14
0
static int CloseMidiOutDevice_(CSOUND *csound, void *userData)
{
    PmError retval;

    if (userData != NULL) {
      retval = Pm_Close((PortMidiStream*) userData);
      if (UNLIKELY(retval != pmNoError)) {
        return portMidiErrMsg(csound, Str("error closing output device"));
      }
    }
    return 0;
}
Example #15
0
void FLiveEditorManager::CloseDeviceConnections()
{
	for( TMap< PmDeviceID, FLiveEditorDeviceInstance >::TIterator It(InputConnections); It; ++It )
	{
		FLiveEditorDeviceInstance Instance = (*It).Value;
		if ( Instance.Connection.MIDIStream )
		{
			Pm_Close( Instance.Connection.MIDIStream );
		}
	}
	InputConnections.Empty();
}
Example #16
0
static ERL_NIF_TERM do_close(ErlNifEnv* env, int arc, const ERL_NIF_TERM argv[]) {
  static PortMidiStream ** stream;

  ErlNifResourceType* streamType = (ErlNifResourceType*)enif_priv_data(env);
  if(!enif_get_resource(env, argv[0], streamType, (PortMidiStream **) &stream)) {
    return enif_make_badarg(env);
  }

  Pm_Close(*stream);

  return enif_make_atom(env, "ok");
}
Example #17
0
MIDIInput::~MIDIInput()
{
	mRunning = NO;
    
    if (mStream) {
        Pm_Close(mStream);
        mStream = NULL;
    }
    
	if (mPollingThread)
		mPollingThread->wait();
	delete mPollingThread;
}
Example #18
0
MIDIController::~MIDIController()
{
	sending_data = false;
	keep_polling = false;

	pthread_mutex_lock(&portmidi_lock);

	pthread_kill(poll_thread, SIGTERM);

	Pm_Close(midi);
	// Pm_Terminate();

	pthread_mutex_unlock(&portmidi_lock);

	pthread_mutex_destroy(&portmidi_lock);
}
Example #19
0
static int CloseMidiInDevice_(CSOUND *csound, void *userData)
{
    PmError retval;
    pmall_data* data = (pmall_data*) userData;
    while (data) {
      retval = Pm_Close(data->midistream);
      if (UNLIKELY(retval != pmNoError)) {
        return portMidiErrMsg(csound, Str("error closing input device"));
      }
      pmall_data* olddata;
      olddata = data;
      data = data->next;
      free(olddata);
    }
    return 0;
}
Example #20
0
void exitFunction() {
  if (isInit) {
    mexPrintf("Terminating PortMidi\n");
    reportPtError(Pt_Stop());
    if (inStream != NULL) {
      reportPmError(Pm_Close(inStream));
      inStream = NULL;
    }
    Pm_Terminate();
    FREE(channel);
    FREE(note);
    FREE(velocity);
    FREE(timestamp);
    isInit = 0;
    deviceOpen = -1;
    numReceived = 0;
  }
}
Example #21
0
TTErr MIDIInput::setName(TTSymbol& newName)
{
	const PmDeviceInfo*	deviceInfo;
    int					i, deviceCount;
	PmError				err = pmNoError;
	
	if (newName != mName) {
        
        // check there is an input with this name
        deviceCount = Pm_CountDevices();
        for (i = 0; i < deviceCount; i++) {
            
            deviceInfo = Pm_GetDeviceInfo(i);
            
            if (deviceInfo->input && newName == TTSymbol(deviceInfo->name))
                break;
        }
        
        if (i == deviceCount)
            return kTTErrGeneric;
		
		mName = newName;
        
        setRunning(NO);
		
		if (mStream) {
			Pm_Close(mStream);
			mStream = NULL;
		}
		
		err = Pm_OpenInput(&mStream, i, NULL, kMidiBufferSize, NULL, NULL);
		if (err) {
            
			TTLogError("MIDIInput::setName : can't open the %s device\n", mName.c_str());
            return kTTErrGeneric;
        }
	}
    
	return kTTErrNone;
}
Example #22
0
MIDIController::MIDIController(const DataSource& __source,
		unsigned int device, unsigned int channel) : source(__source)
{
	keep_polling  = true;

	const PmDeviceInfo* info = Pm_GetDeviceInfo(device);
	assert(info != 0);
	assert(info->output != 0);
	assert(channel < 16);

	this->midi_device  = device;
	this->channel = channel;
	this->midi = NULL;
	this->sending_data = false;

	mute.resize(8);
	for(unsigned int i=0;i<8;i++){
		mute[i] = true; // don't send anything initially
	}

	if(pthread_mutex_init(&portmidi_lock, NULL) != 0){
		throw std::runtime_error("Cannot initialize emotiv mutex.");
	}

	// no latency [TODO: check for errors]
	if(Pm_OpenOutput(&midi, midi_device, NULL, 0, NULL, NULL, 0) != pmNoError){
		pthread_mutex_destroy(&portmidi_lock);
		throw std::runtime_error("Opening MIDI device failed (portmidi).");
	}


	if(pthread_create(&poll_thread, NULL, __midicontroller_thread, (void*)this) != 0){
		pthread_mutex_destroy(&portmidi_lock);
		Pm_Close(midi);
		throw std::runtime_error("Starting thread failed.");
	}
}
Example #23
0
/*
-------------------------------------------------------------
*/
int prDisconnectMIDIIn(struct VMGlobals *g, int numArgsPushed)
{
	ScopeMutexLock mulo(&gPmStreamMutex); 

	PyrSlot *b = g->sp - 1;
	PyrSlot *c = g->sp;

	int err, inputIndex, uid;
	err = slotIntVal(b, &inputIndex);
	if (err) return err;
	if (inputIndex < 0 || inputIndex >= gNumMIDIInPorts) return errIndexOutOfRange;
	err = slotIntVal(c, &uid);
	if (err) 
	return err;

	PmError pmerr = Pm_Close(gMIDIInStreams[uid]);

	if(pmerr != pmNoError)
	return errFailed;

	gMIDIInStreams[uid] = NULL;
	return errNone;

}
/*!
 @function close_midi_out
 @abstract
 @discussion
 @param
 @result
 */
void close_midi_out(PortMidiStream *out)
{
    Pm_Close(out);
}
Example #25
0
QMidiSequencer::~QMidiSequencer()
{
    Pm_Close(m_midi);
}
Example #26
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  int code = 'L';
  PmError err1;
  PtError err2;
  
  init(); /* this returns immediately if already done */
  
  if (nrhs > 0) {
    char arg[2];
    if (!mxIsChar(prhs[0]) || mxGetNumberOfElements(prhs[0]) > 1) {
      mexErrMsgTxt("Bad call\n");
    }
    mxGetString(prhs[0], arg, 2);
    code = arg[0];
  }
  
  switch(code) {
    case 'V':
      if (inStream == NULL) {
        mexErrMsgTxt("No MIDI input device is opened");
      } else {
        if (nrhs < 2) mexErrMsgTxt("Usage for 'verbose': midiIn('V', value)");
        verbose = mxGetScalar(prhs[1]);
      }
      break;
    case 'G': /* Return the buffered events as array */
      if (inStream == NULL) {
        mexErrMsgTxt("No MIDI input device is opened");
      } else {
        plhs[0] = getEvent();
      }
      break;
    case 'F': /* Flush all buffered events */
      if (inStream == NULL) {
        mexErrMsgTxt("No MIDI input device is opened");
      } else {
        /* reset the counter to the beginning of the buffer */
        numReceived = 0;
      }
      break;
    case 'C':   /* Close input stream */
      if (inStream == NULL) {
        mexWarnMsgTxt("No MIDI input device is opened - ignoring 'close' command");
      } else {
        err1 = Pm_Close(inStream);
        inStream = NULL;
        if (err1 != pmNoError) reportPmError(err1);
      }
      break;
    case 'O':	/* Open input stream */
    {
      int device = 0;
      
      if (nrhs<2 || !mxIsNumeric(prhs[1])) mexErrMsgTxt("Bad call\n");
      device = (int) mxGetScalar(prhs[1]);
      if (device < 1 || device > Pm_CountDevices()) mexErrMsgTxt("Device index out of range");
      --device;
      
      if (inStream != NULL) {
        if (deviceOpen == device) {
          mexWarnMsgTxt("MIDI input device is already open - ignoring request");
          return;
        }
        mexWarnMsgTxt("Another MIDI input device is open - closing that one");
        err1 = Pm_Close(inStream);
        inStream = NULL;
        if (err1 != pmNoError) reportPmError(err1);
      }
      
      err1 = Pm_OpenInput(&inStream, device, NULL, INPUT_BUFFER_SIZE, NULL, NULL);
      if (err1 != pmNoError) {
        inStream = NULL;
        reportPmError(err1);
      }
      
      /* remember which device we just opened */
      deviceOpen = device;
    }
    break;
    case 'L':	/* List devices */
      plhs[0] = getDevices();
      break;
    default:
      mexErrMsgTxt("Bad call\n");
  }
}
Example #27
0
void osd_midi_device_pm::close()
{
	Pm_Close(pmStream);
}
Example #28
0
void SonifyEndSonification()
{
   if (sonMidiStream) Pm_Close(sonMidiStream);
   sonificationStarted = false;
}
Example #29
0
int main()
{
    int id;
    long n;
    const PmDeviceInfo *info;
    char line[STRING_MAX];
    int spin;
    int done = FALSE;

    /* determine what type of test to run */
    printf("begin PortMidi multithread test...\n");
	
    /* note that it is safe to call PortMidi from the main thread for
       initialization and opening devices. You should not make any
       calls to PortMidi from this thread once the midi thread begins.
       to make PortMidi calls.
     */

    /* make the message queues */
    /* messages can be of any size and any type, but all messages in
     * a given queue must have the same size. We'll just use long's
     * for our messages in this simple example
     */
    midi_to_main = Pm_QueueCreate(32, sizeof(long));
    assert(midi_to_main != NULL);
    main_to_midi = Pm_QueueCreate(32, sizeof(long));
    assert(main_to_midi != NULL);

    /* a little test of enqueue and dequeue operations. Ordinarily, 
     * you would call Pm_Enqueue from one thread and Pm_Dequeue from
     * the other. Since the midi thread is not running, this is safe.
     */
    n = 1234567890;
    Pm_Enqueue(midi_to_main, &n);
    n = 987654321;
    Pm_Enqueue(midi_to_main, &n);
	Pm_Dequeue(midi_to_main, &n);
	if (n != 1234567890) {
        exit_with_message("Pm_Dequeue produced unexpected result.");
    }
    Pm_Dequeue(midi_to_main, &n);
	if(n != 987654321) {
        exit_with_message("Pm_Dequeue produced unexpected result.");
    }

    /* always start the timer before you start midi */
    Pt_Start(1, &process_midi, 0); /* start a timer with millisecond accuracy */
    /* the timer will call our function, process_midi() every millisecond */
    
	Pm_Initialize();

    id = Pm_GetDefaultOutputDeviceID();
    info = Pm_GetDeviceInfo(id);
    if (info == NULL) {
        printf("Could not open default output device (%d).", id);
        exit_with_message("");
    }
    printf("Opening output device %s %s\n", info->interf, info->name);

    /* use zero latency because we want output to be immediate */
    Pm_OpenOutput(&midi_out, 
                  id, 
                  DRIVER_INFO,
                  OUTPUT_BUFFER_SIZE,
                  TIME_PROC,
                  TIME_INFO,
                  LATENCY);

    id = Pm_GetDefaultInputDeviceID();
    info = Pm_GetDeviceInfo(id);
    if (info == NULL) {
        printf("Could not open default input device (%d).", id);
        exit_with_message("");
    }
    printf("Opening input device %s %s\n", info->interf, info->name);
    Pm_OpenInput(&midi_in, 
                 id, 
                 DRIVER_INFO,
                 INPUT_BUFFER_SIZE,
                 TIME_PROC,
                 TIME_INFO);

    active = TRUE; /* enable processing in the midi thread -- yes, this
                      is a shared variable without synchronization, but
                      this simple assignment is safe */

    printf("Enter midi input; it will be transformed as specified by...\n");
    printf("%s\n%s\n%s\n",
           "Type 'q' to quit, 'm' to monitor next pitch, t to toggle thru or",
           "type a number to specify transposition.",
		   "Must terminate with [ENTER]");

    while (!done) {
        long msg;
        int len;
        fgets(line, STRING_MAX, stdin);
        /* remove the newline: */
        len = strlen(line);
        if (len > 0) line[len - 1] = 0; /* overwrite the newline char */
        if (strcmp(line, "q") == 0) {
            msg = QUIT_MSG;
            Pm_Enqueue(main_to_midi, &msg);
            /* wait for acknowlegement */
            do {
                spin = Pm_Dequeue(midi_to_main, &msg);
            } while (spin == 0); /* spin */ ;
            done = TRUE; /* leave the command loop and wrap up */
        } else if (strcmp(line, "m") == 0) {
            msg = MONITOR_MSG;
            Pm_Enqueue(main_to_midi, &msg);
            printf("Waiting for note...\n");
            do {
                spin = Pm_Dequeue(midi_to_main, &msg);
            } while (spin == 0); /* spin */ ;
            printf("... pitch is %ld\n", msg);
        } else if (strcmp(line, "t") == 0) {
            /* reading midi_thru asynchronously could give incorrect results,
               e.g. if you type "t" twice before the midi thread responds to
               the first one, but we'll do it this way anyway. Perhaps a more
               correct way would be to wait for an acknowledgement message
               containing the new state. */
            printf("Setting THRU %s\n", (midi_thru ? "off" : "on"));
            msg = THRU_MSG;
            Pm_Enqueue(main_to_midi, &msg);
        } else if (sscanf(line, "%ld", &msg) == 1) {
            if (msg >= -127 && msg <= 127) {
                /* send transposition value */
                printf("Transposing by %ld\n", msg);
                Pm_Enqueue(main_to_midi, &msg);
            } else {
                printf("Transposition must be within -127...127\n");
            }
        } else {
            printf("%s\n%s\n%s\n",
                   "Type 'q' to quit, 'm' to monitor next pitch, or",
                   "type a number to specify transposition.",
				   "Must terminate with [ENTER]");
        }
    }

    /* at this point, midi thread is inactive and we need to shut down
     * the midi input and output
     */
    Pt_Stop(); /* stop the timer */
    Pm_QueueDestroy(midi_to_main);
    Pm_QueueDestroy(main_to_midi);

    /* Belinda! if close fails here, some memory is deleted, right??? */
    Pm_Close(midi_in);
    Pm_Close(midi_out);
    
    printf("finished portMidi multithread test...enter any character to quit [RETURN]...");
    fgets(line, STRING_MAX, stdin);
    return 0;
}
/*!
 @function close_midi_in
 @abstract
 @discussion
 @param
 @result
 */
void close_midi_in(PortMidiStream *in)
{
    Pm_Close(in);
}