#ifndef PORT_MIDI_H #define PORT_MIDI_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * PortMidi Portable Real-Time MIDI Library * PortMidi API Header File * Latest version available at: http://www.cs.cmu.edu/~music/portmidi/ * * Copyright (c) 1999-2000 Ross Bencina and Phil Burk * Copyright (c) 2001 Roger B. Dannenberg * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * Any person wishing to distribute modifications to the Software is * requested to send the modifications to the original developer so that * they can be incorporated into the canonical version. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ /* CHANGELOG FOR PORTMIDI * * 21Jan02 RBD Added tests in Pm_OpenInput() and Pm_OpenOutput() to prevent opening an input as output and vice versa. * Added comments and documentation. * Implemented Pm_Terminate(). * 23Jan02 RBD Fixed bug in pmwinmm.c thru handling * * 15Jun02 BCT changes: * - Added pmHostError text handling. * - For robustness, check PortMidi stream args not NULL. * - Re-C-ANSI-fied code (changed many C++ comments to C style) * - Reorganized code in pmwinmm according to input/output functionality (made * cleanup handling easier to reason about) * - Fixed Pm_Write calls (portmidi.h says these should not return length but Pm_Error) * - Cleaned up memory handling (now system specific data deleted via dictionary * call in PortMidi, allows client to query host errors). * - Added explicit asserts to verify various aspects of pmwinmm implementation behaves as * logic implies it should. Specifically: verified callback routines not reentrant and * all verified status for all unchecked Win32 MMedia API calls perform successfully * - Moved portmidi initialization and clean-up routines into DLL to fix Win32 MMedia API * bug (i.e. if devices not explicitly closed, must reboot to debug application further). * With this change, clients no longer need explicitly call Pm_Initialize, Pm_Terminate, or * explicitly Pm_Close open devices when using WinMM version of PortMidi. * * 30Jun02 RBD Extensive rewrite of sysex handling. It works now. * Extensive reworking of error reporting and error text -- no * longer use dictionary call to delete data; instead, Pm_Open * and Pm_Close clean up before returning an error code, and * error text is saved in a system-independent location. * Wrote sysex.c to test sysex message handling. * * IMPORTANT INFORMATION ABOUT A WIN32 BUG: * * Windows apparently has a serious midi bug -- if you do not close ports, Windows * may crash. PortMidi tries to protect against this by using a DLL to clean up. * * If client exits for example with: * i) assert * ii) Ctrl^c, * then DLL clean-up routine called. However, when client does something * really bad (e.g. assigns value to NULL pointer) then DLL CLEANUP ROUTINE * NEVER RUNS! In this state, if you wait around long enough, you will * probably get the blue screen of death. Can also go into Pview and there will * exist zombie process that you can't kill. * * NOTES ON HOST ERROR REPORTING: * * Host-errors are reported on a per-device basis, i.e. only those routines that receive PortMidi stream * handles check and report errors (ideally, might also want host error reporting on pm_init and pm_term * functions but I understand these are never supposed to fail) * * Host errors come in three flavors: * a) host error * b) host error during callback * c) host error write-thru during callback * First two can occur w/midi input or output devices. b) can only occur on input device that * is passing midi-thru messages, in which case host output error must be checked for more detail. * b) and c) can only happen asynchronously (during callback routines), whereas a) only occurs while * synchronously running PortMidi and any resulting system dependent calls * * Host-error reporting relies on following assumptions: * 1) PortMidi routines won't allow system dependent routines to be called when args are bogus. * Thus, in pmwinmm.c it is safe to assume: * - stream ptr valid * - currently not operating in "has host error" state * 2) Host-error reporting relies on one-shot mechanism, i.e. once host error occurs, PortMidi stream * keeps this state until client reads and clears it (thus host error isn't lost). In order * to ensure one-shot invariant, any subsequent Win32 MMedia calls that PortMidi might * wish to execute are dropped (similar scheme is used to keep track of asynchronous host errors * that arise in callbacks). Before any such calls can be executed, client must clear host error * (via Pm_GetHostErrorText or DebugStream). * */ #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif /* default size of buffers for sysex transmission: */ #define PM_DEFAULT_SYSEX_BUFFER_SIZE 1024 typedef enum { pmNoError = 0, pmHostError = -10000, pmInvalidDeviceId, /* out of range or output device when input is requested or vice versa */ pmInsufficientMemory, pmBufferTooSmall, pmBufferOverflow, pmBadPtr, pmInternalError } PmError; /* Pm_Initialize() is the library initialisation function - call this before using the library. */ PmError Pm_Initialize( void ); /* Pm_Terminate() is the library termination function - call this after using the library. */ PmError Pm_Terminate( void ); /* A single PortMidiStream is a descriptor for an open MIDI device. */ typedef void PortMidiStream; #define PmStream PortMidiStream /* Test whether stream has a pending host error. Normally, the client finds out about errors through returned error codes, but some errors can occur asynchronously or during a MIDI "thru" operation where the client does not explicitly call a function, and therefore cannot receive an error code. The client can test for a pending error using Pm_HasHostError(). If true, the error can be accessed and cleared by calling Pm_GetErrorText(). The client does not need to call Pm_HasHostError(). Any pending error will be reported the next time the client performs an explicit function call on the stream, e.g. an input or output operation. */ int Pm_HasHostError( PortMidiStream * stream ); /* Translate portmidi error number into human readable message. These strings are constants (set at compile time) so client has no need to allocate storage */ const char *Pm_GetErrorText( PmError errnum ); /* Translate portmidi host error into human readable message. These strings are not constants (determined at run time) so client has to allocate storage. After this routine executes, host error cleared. Normally, the host error code is retained within an open stream, and only the host error for that stream is cleared (other host errors may exist or even occur asynchronously on other streams). However, if Pm_OpenInput or Pm_OpenOuput returns pmHostError, the host error code is not stored with the stream because there is no valid stream yet. Nevertheless, you can call this function after Pm_OpenInput or Pm_OpenOutput return a pmHostError to get the host error string. */ void Pm_GetHostErrorText(PortMidiStream * stream, char * msg, unsigned int len); #define HDRLENGTH 50 #define PM_HOST_ERROR_MSG_LEN 256 /* any host error msg will occupy less than this number of characters */ /* Device enumeration mechanism. Device ids range from 0 to Pm_CountDevices()-1. Devices may support input, output or both. Device 0 is always the "default" device. Other platform specific devices are specified by positive device ids. */ typedef int PmDeviceID; #define pmNoDevice -1 typedef struct { int structVersion; const char *interf; const char *name; int input; /* true iff input is available */ int output; /* true iff output is available */ int opened; /* used by generic PortMidi code to do error checking on arguments */ } PmDeviceInfo; int Pm_CountDevices( void ); /* Pm_GetDefaultInputDeviceID(), Pm_GetDefaultOutputDeviceID() Return the default device ID or pmNoDevice if there are no devices. The result can be passed to Pm_OpenMidi(). On the PC, the user can specify a default device by setting an environment variable. For example, to use device #1. set PM_RECOMMENDED_OUTPUT_DEVICE=1 The user should first determine the available device ID by using the supplied application "testin" or "testout". In general, the registry is a better place for this kind of info, and with USB devices that can come and go, using integers is not very reliable for device identification. Under Windows, if PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is *NOT* found in the environment, then the default device is obtained by looking for a string in the registry under: HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device for a string. The number of the first device with a substring that matches the string exactly is returned. For example, if the string in the registry is "USB", and device 1 is named "In USB MidiSport 1x1", then that will be the default input because it contains the string "USB". In addition to the name, PmDeviceInfo as the member "interf", which is the interface name. At present, the only interface is "MMSystem". To specify both the interface and the device name in the registry, separate the two with a comma and a space, e.g.: MMSystem, In USB MidiSport 1x1 In this case, the string before the comma must be a substring of the "interf" string, and the string after the space must be a substring of the "name" name string in order to match the device. Note: this functionality is not implemented in the current release. */ PmDeviceID Pm_GetDefaultInputDeviceID( void ); PmDeviceID Pm_GetDefaultOutputDeviceID( void ); /* PmTimestamp is used to represent a millisecond clock with arbitrary start time. The type is used for all MIDI timestampes and clocks. */ typedef long PmTimestamp; typedef PmTimestamp (*PmTimeProcPtr)(void *time_info); /* TRUE if t1 before t2 */ #define PmBefore(t1,t2) ((t1-t2) < 0) /* Pm_GetDeviceInfo() returns a pointer to a PmDeviceInfo structure referring to the device specified by id. If id is out of range the function returns NULL. The returned structure is owned by the PortMidi implementation and must not be manipulated or freed. The pointer is guaranteed to be valid between calls to Pm_Initialize() and Pm_Terminate(). */ const PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id ); /* Pm_Open() opens a device; for either input or output. Port is the address of a PortMidiStream pointer which will receive a pointer to the newly opened stream. inputDevice is the id of the device used for input (see PmDeviceID above). inputDriverInfo is a pointer to an optional driver specific data structure containing additional information for device setup or handle processing. inputDriverInfo is never required for correct operation. If not used inputDriverInfo should be NULL. outputDevice is the id of the device used for output (see PmDeviceID above.) outputDriverInfo is a pointer to an optional driver specific data structure containing additional information for device setup or handle processing. outputDriverInfo is never required for correct operation. If not used outputDriverInfo should be NULL. For input, the buffersize specifies the number of input events to be buffered waiting to be read using Pm_Read(). For output, buffersize specifies the number of output events to be buffered waiting for output. (In some cases, PortMidi does not buffer output at all and merely passes data to a lower-level API, in which case buffersize is ignored.) latency is the delay in milliseconds applied to timestamps to determine when the output should actually occur. (If latency is < 0, 0 is assumed.) If latency is zero, timestamps are ignored and all output is delivered immediately. If latency is greater than zero, output is delayed until the message timestamp plus the latency. time_proc is a pointer to a procedure that returns time in milliseconds. It may be NULL, in which case a default millisecond timebase (PortTime) is used. If the application wants to use PortTime, it should start the timer (call Pt_Start) before calling Pm_OpenInput or Pm_OpenOutput. If the application tries to start the timer *after* Pm_OpenInput or Pm_OpenOutput, it may get a ptAlreadyStarted error from Pt_Start, and the application's preferred time resolution and callback function will be ignored. time_proc result values are appended to incoming MIDI data, and time_proc times are used to schedule outgoing MIDI data (when latency is non-zero). time_info is a pointer passed to time_proc. thru points to a PmMidi descriptor opened for output; Midi input will be copied to this output. To disable Midi thru, use NULL. return value: Upon success Pm_Open() returns PmNoError and places a pointer to a valid PortMidiStream in the stream argument. If a call to Pm_Open() fails a nonzero error code is returned (see PMError above) and the value of port is invalid. Any stream that is successfully opened should eventually be closed by calling Pm_Close(). If you close an input stream with a thru stream, the thru (output) stream is not closed. You should close it with another call to Pm_Close(). */ PmError Pm_OpenInput( PortMidiStream** stream, PmDeviceID inputDevice, void *inputDriverInfo, long bufferSize, PmTimeProcPtr time_proc, void *time_info, PmStream* thru ); PmError Pm_OpenOutput( PortMidiStream** stream, PmDeviceID outputDevice, void *outputDriverInfo, long bufferSize, PmTimeProcPtr time_proc, void *time_info, long latency ); /* Pm_SetFilter() sets filters on an open input stream to drop selected input types. By default, only active sensing messages are filtered. To prohibit, say, active sensing and sysex messages, call Pm_SetFilter(PM_FILT_ACTIVE | PM_FILT_SYSEX); */ /* filter active sensing messages (0xFE): */ #define PM_FILT_ACTIVE 1 /* filter system exclusive messages (0xF0): */ #define PM_FILT_SYSEX 2 /* filter clock messages (0xF8 only, does not filter clock start, etc.): */ #define PM_FILT_CLOCK 4 /* Note: there should probably be other message classes */ PmError Pm_SetFilter( PortMidiStream* stream, long filters ); /* Pm_Abort() terminates outgoing messages immediately The caller should immediately close the output port; this call may result in transmission of a partial midi message. There is no abort for Midi input because the user can simply ignore messages in the buffer and close an input device at any time. */ PmError Pm_Abort( PortMidiStream* stream ); /* Pm_Close() closes a midi stream, flushing any pending buffers. */ PmError Pm_Close( PortMidiStream* stream ); /* Pm_Message() encodes a short Midi message into a long word. If data1 and/or data2 are not present, use zero. The port parameter is the index of the Midi port if the device supports more than one. Pm_MessagePort(), Pm_MessageStatus(), Pm_MessageData1(), and Pm_MessageData2() extract fields from a long-encoded midi message. */ #define Pm_Message(status, data1, data2) \ ((((data2) << 16) & 0xFF0000) | \ (((data1) << 8) & 0xFF00) | \ ((status) & 0xFF)) #define Pm_MessageStatus(msg) ((msg) & 0xFF) #define Pm_MessageData1(msg) (((msg) >> 8) & 0xFF) #define Pm_MessageData2(msg) (((msg) >> 16) & 0xFF) /* All midi data comes in the form of PmEvent structures. A sysex message is encoded as a sequence of PmEvent structures, with each structure carrying 4 bytes of the message, i.e. only the first PmEvent carries the status byte. When receiving sysex messages, the sysex message is terminated by either an EOX status byte (anywhere in the 4 byte message) or by a non-real-time status byte in the low order byte of message. If you get a non-real-time status byte, it means the sysex message was somehow truncated. It is permissible to interleave real-time messages within sysex messages. A real-time message within a sysex message can be in any byte position. A real-time message not within a sysex message will always occupy a full PmEvent with the status byte in the low-order byte of the PmEvent message field. The timestamp field is observed when the output port is opened with a non-zero latency. A timestamp of zero means "use the current time", which in turn means to deliver the message with a delay of latency (the latency parameter used when opening the output port.) A sysex message will generally fill many PmEvent structures. Since the data is typically sent to device drivers in aggregates, PortMidi is free to use any or all timestamps. */ typedef long PmMessage; typedef struct { PmMessage message; PmTimestamp timestamp; } PmEvent; /* Pm_Read() retrieves midi data into a buffer, and returns the number of events read. Result is a non-negative number unless an error occurs, in which case a PmError value will be returned. Buffer Overflow The problem: if an input overflow occurs, data will be lost, ultimately because there is no flow control all the way back to the data source. When data is lost, the receiver should be notified and some sort of graceful recovery should take place, e.g. you shouldn't resume receiving in the middle of a long sysex message. With a lock-free fifo, which is pretty much what we're stuck with to enable portability to the Mac, it's tricky for the producer and consumer to synchronously reset the buffer and resume normal operation. Solution: the buffer managed by PortMidi will be flushed when an overflow occurs. The consumer (Pm_Read()) gets an error message (pmBufferOverflow) and ordinary processing resumes as soon as a new message arrives. The remainder of a partial sysex message is not considered to be a "new message" and will be flushed as well. */ PmError Pm_Read( PortMidiStream *stream, PmEvent *buffer, long length ); /* Pm_Poll() tests whether input is available, returning TRUE, FALSE, or an error value. */ PmError Pm_Poll( PortMidiStream *stream); /* Pm_Write() writes midi data from a buffer. This may contain: - short messages or - sysex messages that are converted into a sequence of PmEvent structures, e.g. sending data from a file or forwarding them from midi input. Use Pm_WriteSysEx() to write a sysex message stored as a contiguous array of bytes. Sysex data may contain embedded real-time messages. */ PmError Pm_Write( PortMidiStream *stream, PmEvent *buffer, long length ); /* Pm_WriteShort() writes a timestamped non-system-exclusive midi message. */ PmError Pm_WriteShort( PortMidiStream *stream, PmTimestamp when, long msg); /* Pm_WriteSysEx() writes a timestamped system-exclusive midi message. */ PmError Pm_WriteSysEx( PortMidiStream *stream, PmTimestamp when, unsigned char *msg); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* PORT_MIDI_H */