void MidiInputDeviceMme::MidiInputPortMme::ConnectToMmeMidiSource(const char* MidiSource) {

    // close the old MIDI Input port if it was already opened
    CloseMmeMidiPort();

    MIDIINCAPS midiincaps;
    int NumDevs = midiInGetNumDevs();

    int FoundMidiInDeviceId = -1;
    for(int i=0;i<NumDevs;i++) {
        int res = midiInGetDevCaps(i, &midiincaps, sizeof(MIDIINCAPS));
        if(res == MMSYSERR_NOERROR) {
            if(!strcmp(midiincaps.szPname, MidiSource)) {
                FoundMidiInDeviceId = i;
                break;
            }
        }
    }

    if(FoundMidiInDeviceId == -1) throw MidiInputException("MIDI port connect failed");

    int res;
    res = midiInOpen(&MidiInHandle, FoundMidiInDeviceId, (DWORD_PTR)win32_midiin_callback, (DWORD_PTR)this, CALLBACK_FUNCTION);
    if(res != MMSYSERR_NOERROR) {
        throw MidiInputException("MIDI port connect failed. midiInOpen error");
    }

    MidiInOpened = true;

    /* Store pointer to our input buffer for System Exclusive messages in MIDIHDR */
    midiHdr.lpData = &TmpSysExBuf[0];

    /* Store its size in the MIDIHDR */
    midiHdr.dwBufferLength = MME_MAX_SYSEX_BUF_SIZE;

    /* Flags must be set to 0 */
    midiHdr.dwFlags = 0;

    /* Prepare the buffer and MIDIHDR */
    res = midiInPrepareHeader(MidiInHandle, &midiHdr, sizeof(MIDIHDR));
    if(res != MMSYSERR_NOERROR) {
        CloseMmeMidiPort();
        throw MidiInputException("MIDI port connect failed. midiInPrepareHeader error");
    }

    /* Queue MIDI input buffer */
    res = midiInAddBuffer(MidiInHandle, &midiHdr, sizeof(MIDIHDR));
    if(res != MMSYSERR_NOERROR) {
        CloseMmeMidiPort();
        throw MidiInputException("MIDI port connect failed. midiInAddBuffer error");
    }


    res = midiInStart(MidiInHandle);
    if(res != MMSYSERR_NOERROR) {
        CloseMmeMidiPort();
        throw MidiInputException("MIDI port connect failed, midiInStart failed.");
    }

}
示例#2
0
static void test_midi_infns(HWND hwnd)
{
    HMIDIIN hm;
    MMRESULT rc;
    UINT udev, ndevs = midiInGetNumDevs();

    rc = midiInOpen(&hm, ndevs, 0, 0, CALLBACK_NULL);
    ok(rc==MMSYSERR_BADDEVICEID, "midiInOpen udev>max rc=%s\n", mmsys_error(rc));
    if (!rc) {
        rc = midiInClose(hm);
        ok(!rc, "midiInClose rc=%s\n", mmsys_error(rc));
    }
    if (!ndevs) {
        trace("Found no MIDI IN device\n"); /* no skip for this common situation */
        rc = midiInOpen(&hm, MIDIMAPPER, 0, 0, CALLBACK_NULL);
        ok(rc==MMSYSERR_BADDEVICEID || broken(rc==MMSYSERR_NODRIVER /*nt,w2k*/), "midiInOpen MAPPER with no MIDI rc=%s\n", mmsys_error(rc));
        if (!rc) {
            rc = midiInClose(hm);
            ok(!rc, "midiInClose rc=%s\n", mmsys_error(rc));
        }
        return;
    }
    trace("Found %d MIDI IN devices\n", ndevs);
    for (udev=0; udev < ndevs; udev++) {
        trace("** Testing device %d\n", udev);
        test_midiIn_device(udev, hwnd);
        Sleep(50);
    }
    trace("** Testing MIDI mapper\n");
    test_midiIn_device(MIDIMAPPER, hwnd);
}
示例#3
0
static void test_midiIn_device(UINT udev, HWND hwnd)
{
    HMIDIIN hm;
    MMRESULT rc;
    MIDIINCAPSA capsA;
    MIDIHDR mhdr;

    rc = midiInGetDevCapsA(udev, &capsA, sizeof(capsA));
    ok((MIDIMAPPER==udev) ? (rc==MMSYSERR_BADDEVICEID || broken(rc==MMSYSERR_NODRIVER /*nt,w2k*/)) : rc==0,
       "midiInGetDevCaps(dev=%d) rc=%s\n", udev, mmsys_error(rc));
    if (!rc) {
        /* MIDI IN capsA.dwSupport may contain garbage, absent in old MS-Windows */
        trace("* %s: manufacturer=%d, product=%d, support=%X\n", capsA.szPname, capsA.wMid, capsA.wPid, capsA.dwSupport);
    }

    if (hwnd)
        rc = midiInOpen(&hm, udev, (DWORD_PTR)hwnd, (DWORD_PTR)MYCBINST, CALLBACK_WINDOW);
    else
        rc = midiInOpen(&hm, udev, (DWORD_PTR)callback_func, (DWORD_PTR)MYCBINST, CALLBACK_FUNCTION);
    ok((MIDIMAPPER!=udev) ? rc==0 : (rc==MMSYSERR_BADDEVICEID || broken(rc==MMSYSERR_NODRIVER /*nt,w2k*/)),
       "midiInOpen(dev=%d) rc=%s\n", udev, mmsys_error(rc));
    if (rc) return;

    test_notification(hwnd, "midiInOpen", MIM_OPEN, 0);

    memset(&mhdr, 0, sizeof(mhdr));
    mhdr.dwFlags = 0;
    mhdr.dwUser = 0x56FA552C;
    mhdr.dwBufferLength = 70000; /* > 64KB! */
    mhdr.lpData = HeapAlloc(GetProcessHeap(), 0 , mhdr.dwBufferLength);
    ok(mhdr.lpData!=NULL, "No %d bytes of memory!\n", mhdr.dwBufferLength);
    if (mhdr.lpData) {
        rc = midiInPrepareHeader(hm, &mhdr, offsetof(MIDIHDR,dwOffset)-1);
        ok(rc==MMSYSERR_INVALPARAM, "midiInPrepare tiny rc=%s\n", mmsys_error(rc));
        rc = midiInPrepareHeader(hm, &mhdr, offsetof(MIDIHDR,dwOffset));
        ok(!rc, "midiInPrepare old size rc=%s\n", mmsys_error(rc));
        rc = midiInPrepareHeader(hm, &mhdr, sizeof(mhdr));
        ok(!rc, "midiInPrepare rc=%s\n", mmsys_error(rc));
        rc = midiInUnprepareHeader(hm, &mhdr, sizeof(mhdr));
        ok(!rc, "midiInUnprepare rc=%s\n", mmsys_error(rc));
        trace("MIDIHDR flags=%x when unsent\n", mhdr.dwFlags);

        HeapFree(GetProcessHeap(), 0, mhdr.lpData);
    }
    ok(mhdr.dwUser==0x56FA552C, "MIDIHDR.dwUser changed to %lx\n", mhdr.dwUser);

    rc = midiInReset(hm); /* Return any pending buffer */
    ok(!rc, "midiInReset rc=%s\n", mmsys_error(rc));

    rc = midiInClose(hm);
    ok(!rc, "midiInClose rc=%s\n", mmsys_error(rc));
    test_notification(hwnd, "midiInClose", MIM_CLOSE, 0);
    test_notification(hwnd, "midiIn over", 0, WHATEVER);
}
Parameter::Parameter(void)
{
	/* Initialize values */
	for (int i = 0; i < NUM_PARAMETERS; i++)
	{
		value[i] = 0.0f;
		changed[i] = false;
	}

	/* Open Midi device */
	numDevices = midiInGetNumDevs();
	if (numDevices > MAX_NUM_DEVICES) numDevices = MAX_NUM_DEVICES;
	for (unsigned int devID = 0; devID < numDevices; devID++)
	{
		MMRESULT rc;
		rc = midiInOpen(&(midiInDevice[devID]), devID, (DWORD_PTR)MidiInProc, NULL, CALLBACK_FUNCTION);
		/* Create input buffers */
		midiInHeader[devID].lpData = (LPSTR)midiData[devID];
		midiInHeader[devID].dwBufferLength = MIDI_DATA_SIZE;
		midiInHeader[devID].dwFlags = 0;
		rc = midiInPrepareHeader(midiInDevice[devID], &midiInHeader[devID], sizeof(midiInHeader[devID]));
		rc = midiInAddBuffer(midiInDevice[devID], &midiInHeader[devID], sizeof(midiInHeader[devID]));
		rc = midiInStart(midiInDevice[devID]);
	}
}
示例#5
0
/* opens a MIDI-In device, returns handle */
int mididrv_in_open(void)
{
    MMRESULT ret;

    log_message(mididrv_log, "Opening MIDI-In device #%d", midi_in_dev);
    if (handle_in) {
        mididrv_in_close();
    }

    if (midi_in_dev != -1) {
        ret = midiInOpen(&handle_in, midi_in_dev, (DWORD_PTR)midi_callback, 0, CALLBACK_FUNCTION);
        if (ret != MMSYSERR_NOERROR) {
            log_error(mididrv_log, "Cannot open MIDI-In device #%d!", midi_in_dev);
            handle_in = 0;
            return -1;
        }
    } else {
        handle_in = 0;
        return -1;
    }

    /* reset FIFO */
    reset_fifo();

    /* can theoretically return MMSYSERR_INVALHANDLE */
    ret = midiInStart(handle_in);

    return (DWORD)handle_in;
}
示例#6
0
void MidiWinMM::openDevices()
{
	m_inputDevices.clear();
	for( unsigned int i = 0; i < midiInGetNumDevs(); ++i )
	{
		MIDIINCAPS c;
		midiInGetDevCaps( i, &c, sizeof( c ) );
		HMIDIIN hm = 0;
		MMRESULT res = midiInOpen( &hm, i, (DWORD_PTR) &inputCallback,
						(DWORD_PTR) this,
							CALLBACK_FUNCTION );
		if( res == MMSYSERR_NOERROR )
		{
			m_inputDevices[hm] = qstrdup( c.szPname );
			midiInStart( hm );
		}
	}

	m_outputDevices.clear();
	for( unsigned int i = 0; i < midiOutGetNumDevs(); ++i )
	{
		MIDIOUTCAPS c;
		midiOutGetDevCaps( i, &c, sizeof( c ) );
		HMIDIOUT hm = 0;
		MMRESULT res = midiOutOpen( &hm, i, 0, 0, CALLBACK_NULL );
		if( res == MMSYSERR_NOERROR )
		{
			m_outputDevices[hm] = qstrdup( c.szPname );
		}
	}
}
    // Plug-in state update function.
    void ResetPluginIfRequired()
    {
        // Reset only if the number of devices was changed.
        int deviceCount = midiInGetNumDevs();
        if (deviceCount == handles.size()) return;

        // Close the all MIDI handles.
        for (auto& handle : handles) {
            midiInClose(handle);
        }
        handles.resize(0);

        // Clear the message queue.
        std::queue<Message> emptyQueue;
        std::swap(messageQueue, emptyQueue);

        // Enumerate the all MIDI devices.
        for (int i = 0; i < deviceCount; i++) {
            HMIDIIN handle;
            MMRESULT result = midiInOpen(&handle, i, reinterpret_cast<DWORD_PTR>(MyMidiInProc), NULL, CALLBACK_FUNCTION);
            assert(result == MMSYSERR_NOERROR);

            result = midiInStart(handle);
            assert(result == MMSYSERR_NOERROR);

            handles.push_back(handle);
        }
    }
示例#8
0
bool Win32MidiIn::open(MidiSession *midiSession, unsigned int midiDevID) {
	int wResult;

	// Init midiIn port
	wResult = midiInOpen(&hMidiIn, midiDevID, (DWORD_PTR)midiInProc, (DWORD_PTR)midiSession, CALLBACK_FUNCTION);
	if (wResult != MMSYSERR_NOERROR) {
		QMessageBox::critical(NULL, "Win32MidiIn Error", "Failed to open MIDI input port");
		return false;
	}

	// Prepare SysEx midiIn buffer
	MidiInHdr.lpData = (LPSTR)sysexbuf;
	MidiInHdr.dwBufferLength = 4096;
	MidiInHdr.dwFlags = 0L;
	wResult = midiInPrepareHeader(hMidiIn, &MidiInHdr, sizeof(MIDIHDR));
	if (wResult != MMSYSERR_NOERROR) {
		QMessageBox::critical(NULL, "Win32MidiIn Error", "Failed to prepare MIDI buffer header");
		return false;
	}

	// Add SysEx Buffer
	wResult = midiInAddBuffer(hMidiIn, &MidiInHdr, sizeof(MIDIHDR));
	if (wResult != MMSYSERR_NOERROR) {
		QMessageBox::critical(NULL, "Win32MidiIn Error", "Failed to add SysEx buffer");
		return false;
	}
	return midiInStart(hMidiIn) == MMSYSERR_NOERROR;
}
/*
 * new_fluid_winmidi_driver
 */
fluid_midi_driver_t*
new_fluid_winmidi_driver(fluid_settings_t* settings,
			handle_midi_event_func_t handler, void* data)
{
  fluid_winmidi_driver_t* dev;
  MMRESULT res;
  UINT i, err, num;
  MIDIINCAPS in_caps;
  int midi_num = 0;

  /* not much use doing anything */
  if (handler == NULL) {
    FLUID_LOG(FLUID_ERR, "Invalid argument");
    return NULL;
  }

  dev = FLUID_MALLOC(sizeof(fluid_winmidi_driver_t));
  if (dev == NULL) {
    return NULL;
  }

  dev->hmidiin = NULL;
  dev->driver.handler = handler;
  dev->driver.data = data;

  /* check if there any midi devices installed */
  num = midiInGetNumDevs();
  if (num == 0) {
    FLUID_LOG(FLUID_ERR, "no MIDI in devices found");
    goto error_recovery;
  }

  /* find the device */
  for (i = 0; i < num; i++) {
    res = midiInGetDevCaps(i, &in_caps, sizeof(LPMIDIINCAPS));
    if (res == MMSYSERR_NOERROR) {
    }
  }

  /* try opening the device */
  err = midiInOpen(&dev->hmidiin, midi_num,
		   (DWORD) fluid_winmidi_callback,
		   (DWORD) dev, CALLBACK_FUNCTION);
  if (err != MMSYSERR_NOERROR) {
    FLUID_LOG(FLUID_WARN, "Couldn't open MIDI input: %s (error %d)",
	     fluid_winmidi_input_error(err), err);
    goto error_recovery;
  }

  if (midiInStart(dev->hmidiin) != MMSYSERR_NOERROR) {
    FLUID_LOG(FLUID_ERR, "Failed to start the MIDI input. MIDI input not available.");
    goto error_recovery;
  }

  return (fluid_midi_driver_t*) dev;

 error_recovery:
  delete_fluid_winmidi_driver((fluid_midi_driver_t*) dev);
  return NULL;
}
示例#10
0
BOOL CMidiDevice::OpenDevIn(UINT uDeviceInID)
{
	// makes sure the previous device is closed
    CloseDevIn();

    // open midi input device
    MMRESULT Result = midiInOpen(&m_hMidiIn, 
		                  uDeviceInID, 
						  (DWORD)MidiInCallback,
					      (DWORD)this,
					      CALLBACK_FUNCTION
					      );

    // change current state
    if(Result == MMSYSERR_NOERROR)
    {
        m_StateIn = OPENEDIN;
    }
	else
	{
		return FALSE;
	}

	return TRUE;
}
void msw_open_midiin(int nmidiin, int *midiinvec)
{
    UINT  wRtn;
    char szErrorText[256];
    unsigned int i;
    unsigned int ndev = 0;
    /* Allocate a circular buffer for low-level MIDI input.  This buffer
     * is filled by the low-level callback function and emptied by the
     * application.
     */
    lpInputBuffer = AllocCircularBuffer((DWORD)(INPUT_BUFFER_SIZE));
    if (lpInputBuffer == NULL)
    {
        printf("Not enough memory available for input buffer.\n");
        return;
    }

    /* Open all MIDI input devices after allocating and setting up
     * instance data for each device.  The instance data is used to
     * pass buffer management information between the application and
     * the low-level callback function.  It also includes a device ID,
     * a handle to the MIDI Mapper, and a handle to the application's
     * display window, so the callback can notify the window when input
     * data is available.  A single callback function is used to service
     * all opened input devices.
     */
    for (i=0; (i<(unsigned)nmidiin) && (i<MAXMIDIINDEV); i++)
    {
        if ((lpCallbackInstanceData[ndev] = AllocCallbackInstanceData()) == NULL)
        {
            printf("Not enough memory available.\n");
            FreeCircularBuffer(lpInputBuffer);
            return;
        }
        lpCallbackInstanceData[i]->dwDevice = i;
        lpCallbackInstanceData[i]->lpBuf = lpInputBuffer;
        
        wRtn = midiInOpen((LPHMIDIIN)&hMidiIn[ndev],
              midiinvec[i],
              (DWORD)midiInputHandler,
              (DWORD)lpCallbackInstanceData[ndev],
              CALLBACK_FUNCTION);
        if (wRtn)
        {
            FreeCallbackInstanceData(lpCallbackInstanceData[ndev]);
            msw_midiinerror("midiInOpen: %s\n", wRtn);
        }
        else ndev++;
    }

    /* Start MIDI input.
     */
    for (i=0; i<ndev; i++)
    {
        if (hMidiIn[i])
            midiInStart(hMidiIn[i]);
    }
    wNumDevices = ndev;
}
示例#12
0
MMRESULT Midi_MasterInOpen(MIDI *midi)
{
    MMRESULT error;

    if (midi->masterInPort == -1 || midi->outPort == -1) {
        return MMSYSERR_NOERROR;
    }
    if (midi->masterInPort == midi->inPort) {
        return MMSYSERR_NOERROR;
    }
#ifdef MIDI_THRU
    /*
     * Open the port.
     */
    error = midiInOpen(&midi->midiMasterIn, midi->masterInPort, 0, 0
            , CALLBACK_NULL);
    if (error != MMSYSERR_NOERROR) {
        return error;
    }
    /*
     * Connect the master in port to the output port.
     */
    error = midiConnect((HMIDI) midi->midiMasterIn, midi->midiOut, NULL);
    if (error != MMSYSERR_NOERROR) {
        midiInClose(midi->midiMasterIn);
        return error;
    }
#else
    /*
     * Open the port.
     */
    error = midiInOpen(&midi->midiMasterIn, midi->masterInPort
            , (DWORD) m_MidiMasterInProc, (DWORD) midi, CALLBACK_FUNCTION);
    if (error != MMSYSERR_NOERROR) {
        return error;
    }
#endif
    error = midiInStart(midi->midiMasterIn);
    if (error != MMSYSERR_NOERROR) {
        midiInReset(midi->midiMasterIn);
        midiInClose(midi->midiMasterIn);
        return error;
    }

    return error;
}
示例#13
0
int rtsyn_synth_start(){
	int i;
	UINT port;

#ifdef __W32__
	DWORD processPriority;
	processPriority = GetPriorityClass(GetCurrentProcess());
#endif

	
	port=0;
	sleep(2);
	for(port=0;port<rtsyn_portnumber;port++){
		for (i=0;i<MAX_EXBUF;i++){
			IMidiHdr[port][i] = (MIDIHDR *)sIMidiHdr[port][i];
			memset(IMidiHdr[port][i],0,sizeof(MIDIHDR));
			IMidiHdr[port][i]->lpData = sImidiHdr_data[port][i];
			memset((IMidiHdr[port][i]->lpData),0,BUFF_SIZE);
			IMidiHdr[port][i]->dwBufferLength = BUFF_SIZE;
		}
	}
	evbwpoint=0;
	evbrpoint=0;
	mvbuse=0;

	for(port=0;port<rtsyn_portnumber;port++){
		midiInOpen(&hMidiIn[port],portID[port],(DWORD)MidiInProc,(DWORD)port,CALLBACK_FUNCTION);
		for (i=0;i<MAX_EXBUF;i++){
			midiInUnprepareHeader(hMidiIn[port],IMidiHdr[port][i],sizeof(MIDIHDR));
			midiInPrepareHeader(hMidiIn[port],IMidiHdr[port][i],sizeof(MIDIHDR));
			midiInAddBuffer(hMidiIn[port],IMidiHdr[port][i],sizeof(MIDIHDR));
		}
	}

#ifdef __W32__
	// HACK:midiInOpen()でリセットされてしまうため、再設定
	SetPriorityClass(GetCurrentProcess(), processPriority);
#endif
	for(port=0;port<rtsyn_portnumber;port++){
		if(MMSYSERR_NOERROR !=midiInStart(hMidiIn[port])){
			int i;
			for(i=0;i<port;i++){
				midiInStop(hMidiIn[i]);
				midiInReset(hMidiIn[i]);
				midiInClose(hMidiIn[i]);
			}
			goto winmmerror;
		}
	}
	mim_start_time = get_current_calender_time();
	InitializeCriticalSection(&mim_section);
	return ~0;

winmmerror:
	ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "midiInStarterror\n" );
	return 0;
}
示例#14
0
MMRESULT Midi_InOpen(MIDI *midi)
{
    MMRESULT error;
    int i;

    if (midi->inPort == -1) {
        return MMSYSERR_NOERROR;
    }
    /*
     * Open the port.
     */
    m_closing = FALSE;
    error = midiInOpen(&midi->midiIn, midi->inPort
            , (DWORD) m_MidiInProc, (DWORD) midi, CALLBACK_FUNCTION);
    if (error != MMSYSERR_NOERROR) {
        return error;
    }
    /*
     * Initialize the midi header array.
     */
    for (i = 0; i < midi->bufCnt; i++) {
        error = midiInPrepareHeader(midi->midiIn, &midi->midiHdrs[i]
                , sizeof(MIDIHDR));
        if (error != MMSYSERR_NOERROR) {
            for (i--; i >= 0; i--) {
                midiInUnprepareHeader(midi->midiIn, &midi->midiHdrs[i]
                        , sizeof(MIDIHDR));
            }
            midiInClose(midi->midiIn);
            return error;
        }
        error = midiInAddBuffer(midi->midiIn, &midi->midiHdrs[i]
                , sizeof(MIDIHDR));
        if (error != MMSYSERR_NOERROR) {
            midiInReset(midi->midiIn);
            for ( ; i >= 0; i--) {
                midiInUnprepareHeader(midi->midiIn, &midi->midiHdrs[i]
                        , sizeof(MIDIHDR));
            }
            midiInClose(midi->midiIn);
            return error;
        }
    }
    /*
     * Initiate MIDI input.
     */
    error = midiInStart(midi->midiIn);
    if (error != MMSYSERR_NOERROR) {
        midiInReset(midi->midiIn);
        midiInClose(midi->midiIn);
        return error;
    }

    return error;
}
示例#15
0
文件: MidiDevice.cpp 项目: EQ4/neonv2
//---------------------------------------------------------------------------//
// Init
//
//---------------------------------------------------------------------------//
bool CMidiDevice::Init(int iDevice)
{
    m_Ok = false;
    if (midiInOpen(&m_MidiIn, iDevice, (DWORD_PTR)MidiDataCallback, (DWORD_PTR)this, CALLBACK_FUNCTION) == MMSYSERR_NOERROR)
    {
        if (midiInStart(m_MidiIn) == MMSYSERR_NOERROR)
            m_Ok = true;
        else
            midiInClose(m_MidiIn);
    }
    return m_Ok;
}
示例#16
0
void midiInitialize(char *inputDeviceStr, char *outputDeviceStr) {
  int inputDevice = atoi(inputDeviceStr);
  int outputDevice = atoi(outputDeviceStr);
  char name[256];
  getOutDeviceName(outputDevice, name, sizeof(name));
  unsigned long result = midiOutOpen(&outHandle, outputDevice, 0, 0, CALLBACK_NULL);
  if (result) {
    logPrintf(LOG_ERROR,
	      "Error opening output device %s with ID %d, aborting\n", name, outputDevice);
    exit(-1);
  } else {
    debugPrintf(1, "Opened output device %s.\n", name);
  }

  getInDeviceName(inputDevice, name, sizeof(name));
  result = midiInOpen(&inHandle, inputDevice, (DWORD)midiCallback, 0, CALLBACK_FUNCTION);
  if (result) {
    logPrintf(LOG_ERROR,
	      "Error opening input device %s with ID %d, aborting\n", name, inputDevice);
    exit(-1);
  } else {
    debugPrintf(1, "Opened input device %s.\n", name);
  }

  sleepCount = 0;
  
  midiHdr.lpData = inputBuffer;
  midiHdr.dwBufferLength = sizeof(inputBuffer);
  midiHdr.dwFlags = 0;
  result = midiInPrepareHeader(inHandle, &midiHdr, sizeof(MIDIHDR));

  if (result) {
    logPrintf(LOG_ERROR, "Could not prepare input buffer\n");
    exit(-1);
  }

  result = midiInAddBuffer(inHandle, &midiHdr, sizeof(MIDIHDR));

  if (result) {
    logPrintf(LOG_ERROR, "could not add input buffer\n");
    exit(-1);
  }

  result = midiInStart(inHandle);
  if (result) {
    logPrintf(LOG_ERROR, "Could not start recording on input\n");
    exit(-1);
  }
}
示例#17
0
文件: Midi_w32.cpp 项目: berak/e6
		bool  _open( uint _deviceID )
		{
			if ( _midiIn ) 
			{
				return true; // shared
			}

			MMRESULT res = 0;
			DWORD_PTR hinst = (DWORD_PTR)::GetModuleHandle(NULL);

			res = midiInOpen( &_midiIn, _deviceID, (DWORD_PTR)_midiInProc, hinst, CALLBACK_FUNCTION );
			if ( res ) return _error( res );   

			res = midiInStart( _midiIn );
			return _error( res ) ;   
		}
示例#18
0
MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
{
    if (callback == nullptr)
        return nullptr;

    UINT deviceId = MIDI_MAPPER;
    int n = 0;
    String name;

    const int num = midiInGetNumDevs();

    for (int i = 0; i < num; ++i)
    {
        MIDIINCAPS mc = { 0 };

        if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
        {
            if (index == n)
            {
                deviceId = i;
                name = String (mc.szPname, numElementsInArray (mc.szPname));
                break;
            }

            ++n;
        }
    }

    ScopedPointer <MidiInput> in (new MidiInput (name));
    ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));

    HMIDIIN h;
    HRESULT err = midiInOpen (&h, deviceId,
                              (DWORD_PTR) &MidiInCollector::midiInCallback,
                              (DWORD_PTR) (MidiInCollector*) collector,
                              CALLBACK_FUNCTION);

    if (err == MMSYSERR_NOERROR)
    {
        collector->deviceHandle = h;
        in->internal = collector.release();
        return in.release();
    }

    return nullptr;
}
示例#19
0
void MidiUartWinClass::init(int _inputDevice, int _outputDevice) {
  MidiUartHostParent::init(_inputDevice, _outputDevice);
	
  unsigned long result;
  char name[256];
  getOutputDeviceName(outputDevice, name, sizeof(name));
  result = midiOutOpen(&outHandle, outputDevice, 0, 0, CALLBACK_NULL);
  if (result) {
    throw "Error opening utput device";
  } else {
    printf("Opened output device %s\n", name);
  }

  getInputDeviceName(inputDevice, name, sizeof(name));
  result = midiInOpen(&inHandle, inputDevice, (DWORD)midiCallback, (DWORD)this, CALLBACK_FUNCTION);
  if (result) {
    throw "Error opening input devic";
  } else {
    printf("Opening input device %s\n", name);
  }

  midiHdr.lpData = inputBuffer;
  midiHdr.dwBufferLength = sizeof(inputBuffer);
  midiHdr.dwFlags = 0;
  result = midiInPrepareHeader(inHandle, &midiHdr, sizeof(MIDIHDR));
  if (result) {
    throw "Could not prepare input buffer";
  }

  result = midiInAddBuffer(inHandle, &midiHdr, sizeof(MIDIHDR));
  if (result) {
    throw "Could not add input buffer";
  }

  result = midiInStart(inHandle);
  if (result) {
    throw "Could not start recording on input";
  }
}
示例#20
0
		MMRESULT Open(unsigned int deviceId)
		{
			// open midi input
			MMRESULT mmResult;
			mmResult = midiInOpen(&handle, deviceId, DWORD_PTR(Proc), NULL, CALLBACK_FUNCTION);
			if (mmResult)
			{
				char buf[256];
				GetLastErrorMessage(buf, 256);
				DebugPrint("Error opening MIDI input: %s", buf);
				return mmResult;
			}

			// prepare input buffer
			header.lpData = sysexbuffer;
			header.dwBufferLength = sizeof(sysexbuffer);
			header.dwFlags = 0;
			mmResult = midiInPrepareHeader(handle, &header, sizeof(MIDIHDR));
			if (mmResult)
			{
				char buf[256];
				GetLastErrorMessage(buf, 256);
				DebugPrint("Error preparing MIDI header: %s", buf);
				return mmResult;
			}

			// queue input buffer
			mmResult = midiInAddBuffer(handle, &header, sizeof(MIDIHDR));
			if (mmResult)
			{
				char buf[256];
				GetLastErrorMessage(buf, 256);
				DebugPrint("Error adding MIDI input buffer: %s", buf);
				return mmResult;
			}

			return mmResult;
		}
示例#21
0
MInputDeviceWin32::MInputDeviceWin32(int deviceId)
{
	hMidiIn = 0;
	// get the devs caps
	midiInGetDevCaps(deviceId,&midiInCaps,sizeof(MIDIINCAPS));

	// open the device
	HRESULT err = midiInOpen(&hMidiIn,deviceId,(DWORD)MInputDeviceWin32::MidiInProc,reinterpret_cast<DWORD>(this),CALLBACK_FUNCTION);
	switch(err) {
	case MMSYSERR_NOERROR:
		break;

	case MMSYSERR_ALLOCATED: //The specified resource is already allocated.
	case MMSYSERR_BADDEVICEID: // The specified device identifier is out of range.
	case MMSYSERR_INVALFLAG: // The flags specified by dwFlags are invalid.
	case MMSYSERR_INVALPARAM: // The specified pointer or structure is invalid.
	case MMSYSERR_NOMEM: // The system is unable to allocate or lock memory.
	default:
		throw Resound::Exception();
	}
	midiInStart(hMidiIn);

}
示例#22
0
/* midi_win32_in_init:
 */
int midi_win32_in_init(int input, int voices)
{
   MMRESULT hr;
   int id;

   /* deduce our device number from the driver ID code */
   id = (midi_input_driver->id & 0xFF) - 'A';

   /* open midi input device */
   hr = midiInOpen(&midi_in_device, id, (DWORD)midi_in_proc,
		   (DWORD)NULL, CALLBACK_FUNCTION);
   if (hr != MMSYSERR_NOERROR) {
      _TRACE(PREFIX_E "midiInOpen failed (%x)\n", hr);
      midi_win32_in_exit(input);
      return -1;
   }


   midiInReset(midi_in_device);
   midiInStart(midi_in_device);

   return 0;
}
void CALLBACK midi_in_handler(HMIDIIN midi_in, UINT msg_type, DWORD user_data, DWORD midi_msg, DWORD param2)
{
	if (msg_type == MIM_DATA)
	{
		union
		{
			DWORD dwData;
			BYTE bData[4];
		}
		u;

		u.dwData = midi_msg;

		switch (u.bData[0] & 0xF0)
		{
			case 0x80:
			{
				key[u.bData[1]].is_pressed = 0;
				break;
			}
			case 0x90:
			{
				switch (state)
				{
					case STATE_PLAY:
					{
						break;
					}
					case STATE_CHOOSE_KEY_TO_EDIT:
					{
						key_to_edit = u.bData[1];
						break;
					}
					case STATE_CHOOSE_OUTPUT_NOTE:
					{
						key_data[key_to_edit].output_channel = u.bData[0] & 0x0F;
						key_data[key_to_edit].output_note = u.bData[1];
						key_data[key_to_edit].output_velocity = u.bData[2];
						break;
					}
					case STATE_CHOOSE_PATTERN:
					{
						if ((u.bData[1] >= 60) && (u.bData[1] < 72))
						{
							key_data[key_to_edit].pattern[u.bData[1] - 60] = 1;
						}

						break;
					}
				}

				key[u.bData[1]].is_pressed = 1;
				break;
			}
			case 0xB0:
			{
				switch (u.bData[1])
				{
					case 1:
					case 64:
					{
						if ((last_controller_value < 64) && (u.bData[2] >= 64))
						{
							switch (state)
							{
								case STATE_PLAY:
								{
									key_to_edit = -1;
									state = STATE_CHOOSE_KEY_TO_EDIT:
									break;
								}
								case STATE_CHOOSE_KEY_TO_EDIT:
								{
									if (key_to_edit == -1)
									{
										state = STATE_PLAY;
									}
									else
									{
										int i;
										key_data[key_to_edit].output_channel = -1;
										key_data[key_to_edit].output_note = -1;
										key_data[key_to_edit].output_velocity = -1;
										for (i = 0; i < 12; i++) key_data[key_to_edit].pattern[i] = 0;
										state = STATE_CHOOSE_OUTPUT_NOTE:
									}

									break;
								}
								case STATE_CHOOSE_OUTPUT_NOTE:
								{
									if (key_data[key_to_edit].output_channel == -1)
									{
										state = STATE_PLAY;
									}
									else
									{
										state = STATE_CHOOSE_PATTERN:
									}

									break;
								}
								case STATE_CHOOSE_PATTERN_STEPS:
								{
									state = PLAY:
									break;
								}
							}
						}

						last_controller_value = u.bData[2];
						break;
					}
					default:
					{
						break;
					}
				}

				break;
			}
			default:
			{
				break;
			}
		}
	}
}

BOOL WINAPI control_handler(DWORD control_type)
{
	midiInStop(midi_in);
	midiInClose(midi_in);
	midiOutClose(midi_out);
	return FALSE;
}

int main(int argc, char **argv)
{
	int i, j;
	int midi_in_number = 0;
	int midi_out_number = MIDI_MAPPER;

	for (i = 1; i < argc; i++)
	{
		if (strcmp(argv[i], "--in") == 0)
		{
			if (++i >= argc) break;
			sscanf(argv[i], "%d", &midi_in_number);
		}
		else if (strcmp(argv[i], "--out") == 0)
		{
			if (++i >= argc) break;
			sscanf(argv[i], "%d", &midi_out_number);
		}
		else
		{
			printf("Usage: %s [--in <n>] [--out <n>]\n", argv[0]);
			return 1;
		}
	}

	if (midiInOpen(&midi_in, midi_in_number, (DWORD)(midi_in_handler), (DWORD)(NULL), CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
	{
		printf("Cannot open MIDI input port #%d.\n", midi_in_number);
		return 1;
	}

	if (midiOutOpen(&midi_out, midi_out_number, 0, 0, 0) != MMSYSERR_NOERROR)
	{
		printf("Cannot open MIDI output port #%d.\n", midi_out_number);
		return 1;
	}

	for (i = 0; i < 128; i++)
	{
		key_data[i].output_channel = -1;
		key_data[i].output_note = -1;
		key_data[i].output_velocity = -1;
		for (j = 0; j < 12; j++) key_data[i].pattern[j] = 0;
		key_data[i].is_pressed = 0;
	}

	SetConsoleCtrlHandler(control_handler, TRUE);

	midiInStart(midi_in);

	beat_start_time = now();

	while (1)
	{
		now = now();
		beat_duration = 60 / tempo;

		if (state == STATE_PLAY)
		{
			for (i = 0; i < 128; i++)
			{
				if (key_data[i].number_of_steps_in_pattern > 0)
				{
				}
			}
		}

		Sleep(CLOCK_RATE);
	}

	return 0;
}
示例#24
0
void RtMidiIn :: openPort( unsigned int portNumber, const std::string /*portName*/ )
{
  if ( connected_ ) {
    errorString_ = "RtMidiIn::openPort: a valid connection already exists!";
    error( RtError::WARNING );
    return;
  }

  unsigned int nDevices = midiInGetNumDevs();
  if (nDevices == 0) {
    errorString_ = "RtMidiIn::openPort: no MIDI input sources found!";
    error( RtError::NO_DEVICES_FOUND );
  }

  std::ostringstream ost;
  if ( portNumber >= nDevices ) {
    ost << "RtMidiIn::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
    errorString_ = ost.str();
    error( RtError::INVALID_PARAMETER );
  }

  WinMidiData *data = static_cast<WinMidiData *> (apiData_);
  MMRESULT result = midiInOpen( &data->inHandle,
                                portNumber,
                                (DWORD)&midiInputCallback,
                                (DWORD)&inputData_,
                                CALLBACK_FUNCTION );
  if ( result != MMSYSERR_NOERROR ) {
    errorString_ = "RtMidiIn::openPort: error creating Windows MM MIDI input port.";
    error( RtError::DRIVER_ERROR );
  }

  // Allocate and init the sysex buffers.
  for ( int i=0; i<RT_SYSEX_BUFFER_COUNT; ++i ) {
    data->sysexBuffer[i] = (MIDIHDR*) new char[ sizeof(MIDIHDR) ];
    data->sysexBuffer[i]->lpData = new char[ RT_SYSEX_BUFFER_SIZE ];
    data->sysexBuffer[i]->dwBufferLength = RT_SYSEX_BUFFER_SIZE;
    data->sysexBuffer[i]->dwUser = i; // We use the dwUser parameter as buffer indicator
    data->sysexBuffer[i]->dwFlags = 0;

    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 );
    }

    // 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 );
    }
  }

  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 );
  }

  connected_ = true;
}
示例#25
0
MF_API bool MFMidi_OpenInput(MFDevice *pDevice, bool bBuffered, MFMidiEventCallback *pEventCallback)
{
	MFDebug_Assert(pDevice->type == MFDT_MidiInput, "Not a MIDI device!");

	if (pDevice->state == MFDevState_Ready || pDevice->state == MFDevState_Active)
	{
		MFDebug_Warn(1, "Midi input device already opened!");
		return false;
	}
	if (pDevice->state != MFDevState_Available)
	{
		MFDebug_Warn(1, "Unable to open midi input device!");
		return false;
	}

	MFMidiPC_MidiInputDevice *pMidi = (MFMidiPC_MidiInputDevice*)pDevice->pInternal;

	// find and open the device
	// TODO: FIXME! this won't work if there are 2 instances of the same device attached to the PC!!!
	UINT numInputDevices = midiInGetNumDevs();
	UINT i = 0;
	for (; i < numInputDevices; ++i)
	{
		MIDIINCAPS caps;
		MMRESULT r = midiInGetDevCaps(i, &caps, sizeof(caps));
		if (r != MMSYSERR_NOERROR)
			continue;

		if (caps.wMid == pMidi->mid && caps.wPid == pMidi->pid)
			break;
	}
	if (i == numInputDevices)
	{
		MFDebug_Warn(1, MFStr("Midi output device '%s' not found!", pDevice->strings[MFDS_ID]));
		pDevice->state = MFDevState_Unknown; // set this flag?
		return false;
	}

	MMRESULT r = midiInOpen(&pMidi->hMidiIn, i, (DWORD_PTR)MidiInProc, (DWORD_PTR)pDevice, CALLBACK_FUNCTION | MIDI_IO_STATUS);
	if (r != MMSYSERR_NOERROR)
	{
		pMidi->hMidiIn = NULL;
		pDevice->state = MFDevState_Unknown;

		wchar_t errorBuffer[256];
		midiInGetErrorText(r, errorBuffer, sizeof(errorBuffer));
		MFDebug_Warn(1, MFStr("Failed to open MIDI input device: %s", MFString_WCharAsUTF8(errorBuffer)));

		return false;
	}

	MFZeroMemory(&pMidi->sysexRecv, sizeof(pMidi->sysexRecv));
	pMidi->sysexRecv.lpData = (LPSTR)pMidi->sysexRecvBuffer;
	pMidi->sysexRecv.dwBufferLength = sizeof(pMidi->sysexRecvBuffer);
	r = midiInPrepareHeader(pMidi->hMidiIn, &pMidi->sysexRecv, sizeof(pMidi->sysexRecv));
	if (r != MMSYSERR_NOERROR)
	{
		wchar_t errorBuffer[256];
		midiInGetErrorText(r, errorBuffer, sizeof(errorBuffer));
		MFDebug_Warn(1, MFStr("Failed to open MIDI input device: %s", MFString_WCharAsUTF8(errorBuffer)));
	}
	r = midiInAddBuffer(pMidi->hMidiIn, &pMidi->sysexRecv, sizeof(pMidi->sysexRecv));
	if (r != MMSYSERR_NOERROR)
	{
		wchar_t errorBuffer[256];
		midiInGetErrorText(r, errorBuffer, sizeof(errorBuffer));
		MFDebug_Warn(1, MFStr("Failed to open MIDI input device: %s", MFString_WCharAsUTF8(errorBuffer)));
	}

	pMidi->bBuffered = bBuffered;
	pMidi->pEventCallback = pEventCallback;

	pMidi->numAllocated = 256;
	pMidi->pEvents = (MFMidiEvent*)MFHeap_Alloc(sizeof(MFMidiEvent) * pMidi->numAllocated);

	pDevice->state = MFDevState_Ready;

	if (!bBuffered && !pEventCallback)
		MFMidi_Start(pDevice);

	return true;
}
示例#26
0
static PmError winmm_in_open(PmInternal *midi, void *driverInfo)
{
    DWORD dwDevice;
    int i = midi->device_id;
    midiwinmm_type m;
    LPMIDIHDR hdr;
    dwDevice = (DWORD) descriptors[i].descriptor;

    /* create system dependent device data */
    m = (midiwinmm_type) pm_alloc(sizeof(midiwinmm_node)); /* create */
    midi->descriptor = m;
    if (!m) goto no_memory;
    m->handle.in = NULL;
    m->buffers = NULL;
    m->num_buffers = 0;
    m->next_buffer = 0;
    m->last_time = 0;
    m->first_message = TRUE; /* not used for input */
    m->sysex_mode = FALSE;
    m->sysex_word = 0;
    m->sysex_byte_count = 0;
    m->sync_time = 0;
    m->delta = 0;
    m->error = MMSYSERR_NOERROR;
    m->callback_error = MMSYSERR_NOERROR;

    /* open device */
    pm_hosterror = midiInOpen(&(m->handle.in), /* input device handle */
                      dwDevice, /* device ID */
                      (DWORD) winmm_in_callback, /* callback address */
                      (DWORD) midi, /* callback instance data */
                      CALLBACK_FUNCTION); /* callback is a procedure */
    if (pm_hosterror) goto free_descriptor;

    /* allocate first buffer for sysex data */
    hdr = allocate_buffer(PM_DEFAULT_SYSEX_BUFFER_SIZE);
    if (!hdr) goto close_device;
    pm_hosterror = midiInPrepareHeader(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) {
        pm_free(hdr);
        goto close_device;
    }
    pm_hosterror = midiInAddBuffer(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) goto close_device;

    /* allocate second buffer */
    hdr = allocate_buffer(PM_DEFAULT_SYSEX_BUFFER_SIZE);
    if (!hdr) goto close_device;
    pm_hosterror = midiInPrepareHeader(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) {
        pm_free(hdr);
        goto reset_device; /* because first buffer was added */
    }
    pm_hosterror = midiInAddBuffer(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) goto reset_device;

    /* start device */
    pm_hosterror = midiInStart(m->handle.in);
    if (pm_hosterror) goto reset_device;
    return pmNoError;

    /* undo steps leading up to the detected error */
reset_device:
    /* ignore return code (we already have an error to report) */
    midiInReset(m->handle.in); 
close_device:
    midiInClose(m->handle.in); /* ignore return code */
free_descriptor:
    midi->descriptor = NULL;
    pm_free(m);
no_memory:
    if (pm_hosterror) {
        int err = midiInGetErrorText(pm_hosterror, (char *) pm_hosterror_text, 
                                     PM_HOST_ERROR_MSG_LEN);
        assert(err == MMSYSERR_NOERROR);
        return pmHostError;
    }
    /* if !pm_hosterror, then the error must be pmInsufficientMemory */
    return pmInsufficientMemory;
    /* note: if we return an error code, the device will be
       closed and memory will be freed. It's up to the caller
       to free the parameter midi */
}
示例#27
0
static PmError winmm_in_open(PmInternal *midi, void *driverInfo)
{
    DWORD dwDevice;
    int i = midi->device_id;
    int max_sysex_len = midi->buffer_len * 4;
    int num_input_buffers = max_sysex_len / INPUT_SYSEX_LEN;
    midiwinmm_type m;

    dwDevice = (DWORD) descriptors[i].descriptor;

    /* create system dependent device data */
    m = (midiwinmm_type) pm_alloc(sizeof(midiwinmm_node)); /* create */
    midi->descriptor = m;
    if (!m) goto no_memory;
    m->handle.in = NULL;
    m->buffers = NULL; /* not used for input */
    m->num_buffers = 0; /* not used for input */
    m->max_buffers = FALSE; /* not used for input */
    m->buffers_expanded = 0; /* not used for input */
    m->next_buffer = 0; /* not used for input */
    m->buffer_signal = 0; /* not used for input */
    m->last_time = 0;
    m->first_message = TRUE; /* not used for input */
    m->sysex_mode = FALSE;
    m->sysex_word = 0;
    m->sysex_byte_count = 0;
    m->hdr = NULL; /* not used for input */
    m->sync_time = 0;
    m->delta = 0;
    m->error = MMSYSERR_NOERROR;
    /* 4000 is based on Windows documentation -- that's the value used in the
       memory manager. It's small enough that it should not hurt performance even
       if it's not optimal.
     */
    InitializeCriticalSectionAndSpinCount(&m->lock, 4000);
    /* open device */
    pm_hosterror = midiInOpen(
	    &(m->handle.in),  /* input device handle */
	    dwDevice,  /* device ID */
	    (DWORD_PTR) winmm_in_callback,  /* callback address */
	    (DWORD_PTR) midi,  /* callback instance data */
	    CALLBACK_FUNCTION); /* callback is a procedure */
    if (pm_hosterror) goto free_descriptor;

    if (num_input_buffers < MIN_INPUT_BUFFERS)
        num_input_buffers = MIN_INPUT_BUFFERS;
    for (i = 0; i < num_input_buffers; i++) {
        if (allocate_input_buffer(m->handle.in, INPUT_SYSEX_LEN)) {
            /* either pm_hosterror was set, or the proper return code
               is pmInsufficientMemory */
            goto close_device;
        }
    }
    /* start device */
    pm_hosterror = midiInStart(m->handle.in);
    if (pm_hosterror) goto reset_device;
    return pmNoError;

    /* undo steps leading up to the detected error */
reset_device:
    /* ignore return code (we already have an error to report) */
    midiInReset(m->handle.in);
close_device:
    midiInClose(m->handle.in); /* ignore return code */
free_descriptor:
    midi->descriptor = NULL;
    pm_free(m);
no_memory:
    if (pm_hosterror) {
        int err = midiInGetErrorText(pm_hosterror, (char *) pm_hosterror_text,
                                     PM_HOST_ERROR_MSG_LEN);
        assert(err == MMSYSERR_NOERROR);
        return pmHostError;
    }
    /* if !pm_hosterror, then the error must be pmInsufficientMemory */
    return pmInsufficientMemory;
    /* note: if we return an error code, the device will be
       closed and memory will be freed. It's up to the caller
       to free the parameter midi */
}
int main(int argc, char **argv)
{
	int i;
	int midi_in_number = 0;
	int number_of_voices = 64;

	for (i = 1; i < argc; i++)
	{
		if (strcmp(argv[i], "--voices") == 0)
		{
			if (++i == argc) usage(argv[0]);
			number_of_voices = atoi(argv[i]);
		}
		else if (strcmp(argv[i], "--in") == 0)
		{
			if (++i == argc) usage(argv[0]);
		}
		else if (strcmp(argv[i], "--config") == 0)
		{
			if (++i == argc) usage(argv[0]);
		}
		else
		{
			usage(argv[0]);
		}
	}

	SetConsoleCtrlHandler(control_handler, TRUE);

	beatbox = Beatbox_new(number_of_voices);

	for (i = 1; i < argc; i++)
	{
		if (strcmp(argv[i], "--voices") == 0)
		{
			if (++i == argc) usage(argv[0]);
		}
		else if (strcmp(argv[i], "--in") == 0)
		{
			if (++i == argc) usage(argv[0]);
			midi_in_number = atoi(argv[i]);
		}
		else if (strcmp(argv[i], "--config") == 0)
		{
			if (++i == argc) usage(argv[0]);
			Beatbox_loadConfig(beatbox, argv[i]);
		}
		else
		{
			usage(argv[0]);
		}
	}

	Pa_Initialize();
	Pa_OpenDefaultStream(&audio_stream, 0, 2, paFloat32, 44100, 256, 0, compute_audio_handler, NULL);
	Pa_StartStream(audio_stream);

	if (midiInOpen(&midi_in, midi_in_number, (DWORD)(midi_in_handler), (DWORD)(NULL), CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
	{
		printf("Cannot open MIDI input port #%d.\n", midi_in_number);
		return 1;
	}

	midiInStart(midi_in);

	Sleep(INFINITE);
	return 0;
}
示例#29
0
COMMNG cmmidi_create(const OEMCHAR *midiout, const OEMCHAR *midiin,
													const OEMCHAR *module) {

	UINT		opened;
	UINT		id;
	void		(*shortout)(CMMIDI self, UINT32 msg);
	void		(*longout)(CMMIDI self, const UINT8 *msg, UINT leng);
	HMIDIFNOUT	out;
	HMIDIIN		hmidiin = NULL;
	COMMNG		ret;
	CMMIDI		midi;

	opened = 0;
	ZeroMemory(&out, sizeof(out));
	shortout = midi_ncshort;
	longout = midi_nclong;
	if (getmidioutid(midiout, &id) == SUCCESS) {
		if (midiOutOpen(&out.win32.hmidiout, id, 0, 0, CALLBACK_NULL)
														== MMSYSERR_NOERROR) {
			midiOutReset(out.win32.hmidiout);
			shortout = midi_win32short;
			longout = midi_win32long;
			opened |= CMMIDI_MIDIOUT;
		}
	}
	if (getmidiinid(midiin, &id) == SUCCESS) {
		if (midiInOpen(&hmidiin, id, (DWORD)g_hWndMain, 0, CALLBACK_WINDOW)
														== MMSYSERR_NOERROR) {
			midiInReset(hmidiin);
			opened |= CMMIDI_MIDIIN;
		}
	}
#if defined(VERMOUTH_LIB)
	else if (!milstr_cmp(midiout, cmmidi_vermouth)) {
		out.vermouth = midiout_create(vermouth_module, 512);
		if (out.vermouth != NULL) {
			shortout = midi_vermouthshort;
			longout = midi_vermouthlong;
			opened |= CMMIDI_VERMOUTH;
		}
	}
#endif
#if defined(MT32SOUND_DLL)
	else if (!milstr_cmp(midiout, cmmidi_mt32sound)) {
		if (mt32sound_open() == SUCCESS) {
			shortout = midi_mt32short;
			longout = midi_mt32long;
			opened |= CMMIDI_MT32SOUND;
		}
	}
#endif
	if (!opened) {
		goto cmcre_err1;
	}
	ret = (COMMNG)_MALLOC(sizeof(_COMMNG) + sizeof(_CMMIDI), "MIDI");
	if (ret == NULL) {
		goto cmcre_err2;
	}
	ret->connect = COMCONNECT_MIDI;
	ret->read = midiread;
	ret->write = midiwrite;
	ret->getstat = midigetstat;
	ret->msg = midimsg;
	ret->release = midirelease;
	midi = (CMMIDI)(ret + 1);
	ZeroMemory(midi, sizeof(_CMMIDI));
	midi->opened = opened;
	midi->shortout = shortout;
	midi->longout = longout;
	midi->out = out;
	midi->midictrl = MIDICTRL_READY;
#if 1
	midi->hmidiin = hmidiin;
	if (opened & CMMIDI_MIDIIN) {
		if (midiinhdlreg(midi, hmidiin) == SUCCESS) {
			midi->opened |= CMMIDI_MIDIINSTART;
			midi->hmidiinhdr.lpData = (char *)midi->midiinbuf;
			midi->hmidiinhdr.dwBufferLength = MIDI_BUFFER;
			midiInPrepareHeader(hmidiin, &midi->hmidiinhdr, sizeof(MIDIHDR));
			midiInAddBuffer(hmidiin, &midi->hmidiinhdr, sizeof(MIDIHDR));
			midiInStart(hmidiin);
		}
	}
#endif
#if defined(VERMOUTH_LIB)
	if (opened & CMMIDI_VERMOUTH) {
		sound_streamregist((void *)out.vermouth, (SOUNDCB)vermouth_getpcm);
	}
#endif
#if defined(MT32SOUND_DLL)
	if (opened & CMMIDI_MT32SOUND) {
		sound_streamregist(NULL, (SOUNDCB)mt32_getpcm);
	}
#endif
//	midi->midisyscnt = 0;
//	midi->mpos = 0;

	midi->midilast = 0x80;
//	midi->midiexcvwait = 0;
	midi->midimodule = (UINT8)module2number(module);
	FillMemory(midi->mch, sizeof(midi->mch), 0xff);
	return(ret);

cmcre_err2:
	if (opened & CMMIDI_MIDIOUT) {
		midiOutReset(out.win32.hmidiout);
		midiOutClose(out.win32.hmidiout);
	}
#if defined(VERMOUTH_LIB)
	if (opened & CMMIDI_VERMOUTH) {
		midiout_destroy(out.vermouth);
	}
#endif
#if defined(MT32SOUND_DLL)
	if (opened & CMMIDI_MT32SOUND) {
		mt32sound_close();
	}
#endif

cmcre_err1:
	return(NULL);
}
示例#30
0
MOboolean
moMidiDevice::Init( moText devicetext ) {

	SetName(devicetext);


#ifdef WIN32
/*
	BOOL		result;
	GUID		hidGUID;
	HDEVINFO	hardwareDeviceInfoSet;
	SP_DEVICE_INTERFACE_DATA	deviceInterfaceData;
	DWORD Index = 0;
	DWORD requiredSize;

	//Get the HID GUID value - used as mask to get list of devices
	HidD_GetHidGuid ( &hidGUID );

	//Get a list of devices matching the criteria (hid interface, present)
	hardwareDeviceInfoSet = SetupDiGetClassDevs (&hidGUID,
					NULL, // Define no enumerator (global)
					NULL, // Define no
					(DIGCF_PRESENT | DIGCF_ALLCLASSES |DIGCF_DEVICEINTERFACE));


	deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

	//Go through the list and get the interface data
	for(int i = 0; i < 10; i++)
	{
		result = SetupDiEnumDeviceInterfaces (hardwareDeviceInfoSet,
					NULL, //infoData,
					&hidGUID, //interfaceClassGuid,
					Index,
					&deviceInterfaceData);
		if (result == FALSE) {
			Index++;
		}
	}

	// Failed to get a device - possibly the index is larger than the number of devices
	if (result == FALSE) {
		SetupDiDestroyDeviceInfoList (hardwareDeviceInfoSet);
		return;// INVALID_HANDLE_VALUE;
	}

	//Get the details with null values to get the required size of the buffer
	SetupDiGetDeviceInterfaceDetail (hardwareDeviceInfoSet,
				&deviceInterfaceData,
				NULL, //interfaceDetail,
				0, //interfaceDetailSize,
				&requiredSize,
				0); //infoData))
*/

	MIDIINCAPS     moc;
	unsigned long   iNumDevs, i;



	/* Get the number of MIDI Out devices in this computer */
	iNumDevs = midiInGetNumDevs();

	if (iNumDevs==0) {
	    MODebug2->Message( moText("ERROR! NO MIDI DEVICES FOUND"));
    }

	/* Go through all of those devices, displaying their names */
	for (i = 0; i < iNumDevs; i++)
	{
		/* Get info about the next device */
		if (!midiInGetDevCaps(i, &moc, sizeof(MIDIINCAPS)))
		{
			/* Display its Device ID and name */
			MODebug2->Message( moText("Device ID #") + IntToStr(i) + moText(":") + moText(moc.szPname));
			if ( !stricmp(moc.szPname, devicetext) ) {
				m_DeviceId = i;
				break;
			}
		}
	}


	/*
	unsigned long result;
	HMIDIOUT      outHandle;

	// Open the MIDI Mapper
	result = midiOutOpen(&outHandle, i, 0, 0, CALLBACK_WINDOW);
	if (!result)
	{
		// Output the C note (ie, sound the note)
		midiOutShortMsg(outHandle, 0x00403C90);

		// Output the E note
		midiOutShortMsg(outHandle, 0x00404090);

		// Output the G note
		midiOutShortMsg(outHandle, 0x00404390);

		// Here you should insert a delay so that you can hear the notes sounding
		Sleep(1000);

		// Now let's turn off those 3 notes
		midiOutShortMsg(outHandle, 0x00003C90);
		midiOutShortMsg(outHandle, 0x00004090);
		midiOutShortMsg(outHandle, 0x00004390);

		 // Close the MIDI device
		 midiOutClose(outHandle);
	} else {
		printf("There was an error opening MIDI Mapper!\r\n");
	}
	*/
	HMIDIIN			handle;
	MIDIHDR			midiHdr;
	unsigned long	err;

	if (m_DeviceId!=-1) {
		/* Open default MIDI In device */
		if (!(err = midiInOpen(&handle, m_DeviceId, (DWORD)midiCallback, (DWORD)this, CALLBACK_FUNCTION)))
		{
			// Store pointer to our input buffer for System Exclusive messages in MIDIHDR
			midiHdr.lpData = (LPSTR)&SysXBuffer[0];

			// Store its size in the MIDIHDR
			midiHdr.dwBufferLength = sizeof(SysXBuffer);

			// Flags must be set to 0
			midiHdr.dwFlags = 0;

			// Prepare the buffer and MIDIHDR
			err = midiInPrepareHeader(handle, &midiHdr, sizeof(MIDIHDR));
			if (!err)
			{
				// Queue MIDI input buffer
				err = midiInAddBuffer(handle, &midiHdr, sizeof(MIDIHDR));
				if (!err)
				{
					// Start recording Midi
					err = midiInStart(handle);
					m_bInit = true;
					return true;
					/*
					if (!err)
					{
						// Wait for user to abort recording
						printf("Press any key to stop recording...\r\n\n");
						_getch();

						// We need to set a flag to tell our callback midiCallback()
						// not to do any more midiInAddBuffer(), because when we
						// call midiInReset() below, Windows will send a final
						// MIM_LONGDATA message to that callback. If we were to
						// allow midiCallback() to midiInAddBuffer() again, we'd
						// never get the driver to finish with our midiHdr

						SysXFlag |= 0x80;
						printf("\r\nRecording stopped!\n");
					}*/

					/* Stop recording */
					//midiInReset(handle);
				}
			}
	/*
			// If there was an error above, then print a message
			if (err) PrintMidiInErrorMsg(err);

			// Close the MIDI In device
			while ((err = midiInClose(handle)) == MIDIERR_STILLPLAYING) Sleep(0);
			if (err) PrintMidiInErrorMsg(err);

			// Unprepare the buffer and MIDIHDR. Unpreparing a buffer that has not been prepared is ok
			midiInUnprepareHeader(handle, &midiHdr, sizeof(MIDIHDR));
			*/
		}
		else
		{
			printf("Error opening the default MIDI In Device!\r\n");
			PrintMidiInErrorMsg(err);
			return false;
		}
	}

#else

#endif
		return false;
}