portmidi.h (28421B)
1 #ifndef PORT_MIDI_H 2 #define PORT_MIDI_H 3 #ifdef __cplusplus 4 extern "C" { 5 #endif /* __cplusplus */ 6 7 /* 8 * PortMidi Portable Real-Time MIDI Library 9 * PortMidi API Header File 10 * Latest version available at: http://sourceforge.net/projects/portmedia 11 * 12 * Copyright (c) 1999-2000 Ross Bencina and Phil Burk 13 * Copyright (c) 2001-2006 Roger B. Dannenberg 14 * 15 * Permission is hereby granted, free of charge, to any person obtaining 16 * a copy of this software and associated documentation files 17 * (the "Software"), to deal in the Software without restriction, 18 * including without limitation the rights to use, copy, modify, merge, 19 * publish, distribute, sublicense, and/or sell copies of the Software, 20 * and to permit persons to whom the Software is furnished to do so, 21 * subject to the following conditions: 22 * 23 * The above copyright notice and this permission notice shall be 24 * included in all copies or substantial portions of the Software. 25 * 26 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 27 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 28 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 29 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 30 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 31 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 32 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 33 */ 34 35 /* 36 * The text above constitutes the entire PortMidi license; however, 37 * the PortMusic community also makes the following non-binding requests: 38 * 39 * Any person wishing to distribute modifications to the Software is 40 * requested to send the modifications to the original developer so that 41 * they can be incorporated into the canonical version. It is also 42 * requested that these non-binding requests be included along with the 43 * license above. 44 */ 45 46 /* CHANGELOG FOR PORTMIDI 47 * (see ../CHANGELOG.txt) 48 * 49 * NOTES ON HOST ERROR REPORTING: 50 * 51 * PortMidi errors (of type PmError) are generic, system-independent errors. 52 * When an error does not map to one of the more specific PmErrors, the 53 * catch-all code pmHostError is returned. This means that PortMidi has 54 * retained a more specific system-dependent error code. The caller can 55 * get more information by calling Pm_HasHostError() to test if there is 56 * a pending host error, and Pm_GetHostErrorText() to get a text string 57 * describing the error. Host errors are reported on a per-device basis 58 * because only after you open a device does PortMidi have a place to 59 * record the host error code. I.e. only 60 * those routines that receive a (PortMidiStream *) argument check and 61 * report errors. One exception to this is that Pm_OpenInput() and 62 * Pm_OpenOutput() can report errors even though when an error occurs, 63 * there is no PortMidiStream* to hold the error. Fortunately, both 64 * of these functions return any error immediately, so we do not really 65 * need per-device error memory. Instead, any host error code is stored 66 * in a global, pmHostError is returned, and the user can call 67 * Pm_GetHostErrorText() to get the error message (and the invalid stream 68 * parameter will be ignored.) The functions 69 * pm_init and pm_term do not fail or raise 70 * errors. The job of pm_init is to locate all available devices so that 71 * the caller can get information via PmDeviceInfo(). If an error occurs, 72 * the device is simply not listed as available. 73 * 74 * Host errors come in two flavors: 75 * a) host error 76 * b) host error during callback 77 * These can occur w/midi input or output devices. (b) can only happen 78 * asynchronously (during callback routines), whereas (a) only occurs while 79 * synchronously running PortMidi and any resulting system dependent calls. 80 * Both (a) and (b) are reported by the next read or write call. You can 81 * also query for asynchronous errors (b) at any time by calling 82 * Pm_HasHostError(). 83 * 84 * NOTES ON COMPILE-TIME SWITCHES 85 * 86 * DEBUG assumes stdio and a console. Use this if you want automatic, simple 87 * error reporting, e.g. for prototyping. If you are using MFC or some 88 * other graphical interface with no console, DEBUG probably should be 89 * undefined. 90 * PM_CHECK_ERRORS more-or-less takes over error checking for return values, 91 * stopping your program and printing error messages when an error 92 * occurs. This also uses stdio for console text I/O. 93 */ 94 95 #ifndef WIN32 96 // Linux and OS X have stdint.h 97 #include <stdint.h> 98 #else 99 #ifndef INT32_DEFINED 100 // rather than having users install a special .h file for windows, 101 // just put the required definitions inline here. porttime.h uses 102 // these too, so the definitions are (unfortunately) duplicated there 103 typedef int int32_t; 104 typedef unsigned int uint32_t; 105 #define INT32_DEFINED 106 #endif 107 #endif 108 109 #ifdef _WINDLL 110 #define PMEXPORT __declspec(dllexport) 111 #else 112 #define PMEXPORT 113 #endif 114 115 #ifndef FALSE 116 #define FALSE 0 117 #endif 118 #ifndef TRUE 119 #define TRUE 1 120 #endif 121 122 /* default size of buffers for sysex transmission: */ 123 #define PM_DEFAULT_SYSEX_BUFFER_SIZE 1024 124 125 /** List of portmidi errors.*/ 126 typedef enum { 127 pmNoError = 0, 128 pmNoData = 0, /**< A "no error" return that also indicates no data avail. */ 129 pmGotData = 1, /**< A "no error" return that also indicates data available */ 130 pmHostError = -10000, 131 pmInvalidDeviceId, /** out of range or 132 * output device when input is requested or 133 * input device when output is requested or 134 * device is already opened 135 */ 136 pmInsufficientMemory, 137 pmBufferTooSmall, 138 pmBufferOverflow, 139 pmBadPtr, /* PortMidiStream parameter is NULL or 140 * stream is not opened or 141 * stream is output when input is required or 142 * stream is input when output is required */ 143 pmBadData, /** illegal midi data, e.g. missing EOX */ 144 pmInternalError, 145 pmBufferMaxSize /** buffer is already as large as it can be */ 146 /* NOTE: If you add a new error type, be sure to update Pm_GetErrorText() */ 147 } PmError; 148 149 /** 150 Pm_Initialize() is the library initialisation function - call this before 151 using the library. 152 */ 153 PMEXPORT PmError Pm_Initialize( void ); 154 155 /** 156 Pm_Terminate() is the library termination function - call this after 157 using the library. 158 */ 159 PMEXPORT PmError Pm_Terminate( void ); 160 161 /** A single PortMidiStream is a descriptor for an open MIDI device. 162 */ 163 typedef void PortMidiStream; 164 #define PmStream PortMidiStream 165 166 /** 167 Test whether stream has a pending host error. Normally, the client finds 168 out about errors through returned error codes, but some errors can occur 169 asynchronously where the client does not 170 explicitly call a function, and therefore cannot receive an error code. 171 The client can test for a pending error using Pm_HasHostError(). If true, 172 the error can be accessed and cleared by calling Pm_GetErrorText(). 173 Errors are also cleared by calling other functions that can return 174 errors, e.g. Pm_OpenInput(), Pm_OpenOutput(), Pm_Read(), Pm_Write(). The 175 client does not need to call Pm_HasHostError(). Any pending error will be 176 reported the next time the client performs an explicit function call on 177 the stream, e.g. an input or output operation. Until the error is cleared, 178 no new error codes will be obtained, even for a different stream. 179 */ 180 PMEXPORT int Pm_HasHostError( PortMidiStream * stream ); 181 182 183 /** Translate portmidi error number into human readable message. 184 These strings are constants (set at compile time) so client has 185 no need to allocate storage 186 */ 187 PMEXPORT const char *Pm_GetErrorText( PmError errnum ); 188 189 /** Translate portmidi host error into human readable message. 190 These strings are computed at run time, so client has to allocate storage. 191 After this routine executes, the host error is cleared. 192 */ 193 PMEXPORT void Pm_GetHostErrorText(char * msg, unsigned int len); 194 195 #define HDRLENGTH 50 196 #define PM_HOST_ERROR_MSG_LEN 256u /* any host error msg will occupy less 197 than this number of characters */ 198 199 /** 200 Device enumeration mechanism. 201 202 Device ids range from 0 to Pm_CountDevices()-1. 203 204 */ 205 typedef int PmDeviceID; 206 #define pmNoDevice -1 207 typedef struct { 208 int structVersion; /**< this internal structure version */ 209 const char *interf; /**< underlying MIDI API, e.g. MMSystem or DirectX */ 210 const char *name; /**< device name, e.g. USB MidiSport 1x1 */ 211 int input; /**< true iff input is available */ 212 int output; /**< true iff output is available */ 213 int opened; /**< used by generic PortMidi code to do error checking on arguments */ 214 215 } PmDeviceInfo; 216 217 /** Get devices count, ids range from 0 to Pm_CountDevices()-1. */ 218 PMEXPORT int Pm_CountDevices( void ); 219 /** 220 Pm_GetDefaultInputDeviceID(), Pm_GetDefaultOutputDeviceID() 221 222 Return the default device ID or pmNoDevice if there are no devices. 223 The result (but not pmNoDevice) can be passed to Pm_OpenMidi(). 224 225 The default device can be specified using a small application 226 named pmdefaults that is part of the PortMidi distribution. This 227 program in turn uses the Java Preferences object created by 228 java.util.prefs.Preferences.userRoot().node("/PortMidi"); the 229 preference is set by calling 230 prefs.put("PM_RECOMMENDED_OUTPUT_DEVICE", prefName); 231 or prefs.put("PM_RECOMMENDED_INPUT_DEVICE", prefName); 232 233 In the statements above, prefName is a string describing the 234 MIDI device in the form "interf, name" where interf identifies 235 the underlying software system or API used by PortMdi to access 236 devices and name is the name of the device. These correspond to 237 the interf and name fields of a PmDeviceInfo. (Currently supported 238 interfaces are "MMSystem" for Win32, "ALSA" for Linux, and 239 "CoreMIDI" for OS X, so in fact, there is no choice of interface.) 240 In "interf, name", the strings are actually substrings of 241 the full interface and name strings. For example, the preference 242 "Core, Sport" will match a device with interface "CoreMIDI" 243 and name "In USB MidiSport 1x1". It will also match "CoreMIDI" 244 and "In USB MidiSport 2x2". The devices are enumerated in device 245 ID order, so the lowest device ID that matches the pattern becomes 246 the default device. Finally, if the comma-space (", ") separator 247 between interface and name parts of the preference is not found, 248 the entire preference string is interpreted as a name, and the 249 interface part is the empty string, which matches anything. 250 251 On the MAC, preferences are stored in 252 /Users/$NAME/Library/Preferences/com.apple.java.util.prefs.plist 253 which is a binary file. In addition to the pmdefaults program, 254 there are utilities that can read and edit this preference file. 255 256 On the PC, 257 258 On Linux, 259 260 */ 261 PMEXPORT PmDeviceID Pm_GetDefaultInputDeviceID( void ); 262 /** see PmDeviceID Pm_GetDefaultInputDeviceID() */ 263 PMEXPORT PmDeviceID Pm_GetDefaultOutputDeviceID( void ); 264 265 /** 266 PmTimestamp is used to represent a millisecond clock with arbitrary 267 start time. The type is used for all MIDI timestampes and clocks. 268 */ 269 typedef int32_t PmTimestamp; 270 typedef PmTimestamp (*PmTimeProcPtr)(void *time_info); 271 272 /** TRUE if t1 before t2 */ 273 #define PmBefore(t1,t2) ((t1-t2) < 0) 274 /** 275 \defgroup grp_device Input/Output Devices Handling 276 @{ 277 */ 278 /** 279 Pm_GetDeviceInfo() returns a pointer to a PmDeviceInfo structure 280 referring to the device specified by id. 281 If id is out of range the function returns NULL. 282 283 The returned structure is owned by the PortMidi implementation and must 284 not be manipulated or freed. The pointer is guaranteed to be valid 285 between calls to Pm_Initialize() and Pm_Terminate(). 286 */ 287 PMEXPORT const PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id ); 288 289 /** 290 Pm_OpenInput() and Pm_OpenOutput() open devices. 291 292 stream is the address of a PortMidiStream pointer which will receive 293 a pointer to the newly opened stream. 294 295 inputDevice is the id of the device used for input (see PmDeviceID above). 296 297 inputDriverInfo is a pointer to an optional driver specific data structure 298 containing additional information for device setup or handle processing. 299 inputDriverInfo is never required for correct operation. If not used 300 inputDriverInfo should be NULL. 301 302 outputDevice is the id of the device used for output (see PmDeviceID above.) 303 304 outputDriverInfo is a pointer to an optional driver specific data structure 305 containing additional information for device setup or handle processing. 306 outputDriverInfo is never required for correct operation. If not used 307 outputDriverInfo should be NULL. 308 309 For input, the buffersize specifies the number of input events to be 310 buffered waiting to be read using Pm_Read(). For output, buffersize 311 specifies the number of output events to be buffered waiting for output. 312 (In some cases -- see below -- PortMidi does not buffer output at all 313 and merely passes data to a lower-level API, in which case buffersize 314 is ignored.) 315 316 latency is the delay in milliseconds applied to timestamps to determine 317 when the output should actually occur. (If latency is < 0, 0 is assumed.) 318 If latency is zero, timestamps are ignored and all output is delivered 319 immediately. If latency is greater than zero, output is delayed until the 320 message timestamp plus the latency. (NOTE: the time is measured relative 321 to the time source indicated by time_proc. Timestamps are absolute, 322 not relative delays or offsets.) In some cases, PortMidi can obtain 323 better timing than your application by passing timestamps along to the 324 device driver or hardware. Latency may also help you to synchronize midi 325 data to audio data by matching midi latency to the audio buffer latency. 326 327 time_proc is a pointer to a procedure that returns time in milliseconds. It 328 may be NULL, in which case a default millisecond timebase (PortTime) is 329 used. If the application wants to use PortTime, it should start the timer 330 (call Pt_Start) before calling Pm_OpenInput or Pm_OpenOutput. If the 331 application tries to start the timer *after* Pm_OpenInput or Pm_OpenOutput, 332 it may get a ptAlreadyStarted error from Pt_Start, and the application's 333 preferred time resolution and callback function will be ignored. 334 time_proc result values are appended to incoming MIDI data, and time_proc 335 times are used to schedule outgoing MIDI data (when latency is non-zero). 336 337 time_info is a pointer passed to time_proc. 338 339 Example: If I provide a timestamp of 5000, latency is 1, and time_proc 340 returns 4990, then the desired output time will be when time_proc returns 341 timestamp+latency = 5001. This will be 5001-4990 = 11ms from now. 342 343 return value: 344 Upon success Pm_Open() returns PmNoError and places a pointer to a 345 valid PortMidiStream in the stream argument. 346 If a call to Pm_Open() fails a nonzero error code is returned (see 347 PMError above) and the value of port is invalid. 348 349 Any stream that is successfully opened should eventually be closed 350 by calling Pm_Close(). 351 352 */ 353 PMEXPORT PmError Pm_OpenInput( PortMidiStream** stream, 354 PmDeviceID inputDevice, 355 void *inputDriverInfo, 356 int32_t bufferSize, 357 PmTimeProcPtr time_proc, 358 void *time_info ); 359 360 PMEXPORT PmError Pm_OpenOutput( PortMidiStream** stream, 361 PmDeviceID outputDevice, 362 void *outputDriverInfo, 363 int32_t bufferSize, 364 PmTimeProcPtr time_proc, 365 void *time_info, 366 int32_t latency ); 367 /** @} */ 368 369 /** 370 \defgroup grp_events_filters Events and Filters Handling 371 @{ 372 */ 373 374 /* \function PmError Pm_SetFilter( PortMidiStream* stream, int32_t filters ) 375 Pm_SetFilter() sets filters on an open input stream to drop selected 376 input types. By default, only active sensing messages are filtered. 377 To prohibit, say, active sensing and sysex messages, call 378 Pm_SetFilter(stream, PM_FILT_ACTIVE | PM_FILT_SYSEX); 379 380 Filtering is useful when midi routing or midi thru functionality is being 381 provided by the user application. 382 For example, you may want to exclude timing messages (clock, MTC, start/stop/continue), 383 while allowing note-related messages to pass. 384 Or you may be using a sequencer or drum-machine for MIDI clock information but want to 385 exclude any notes it may play. 386 */ 387 388 /* Filter bit-mask definitions */ 389 /** filter active sensing messages (0xFE): */ 390 #define PM_FILT_ACTIVE (1 << 0x0E) 391 /** filter system exclusive messages (0xF0): */ 392 #define PM_FILT_SYSEX (1 << 0x00) 393 /** filter MIDI clock message (0xF8) */ 394 #define PM_FILT_CLOCK (1 << 0x08) 395 /** filter play messages (start 0xFA, stop 0xFC, continue 0xFB) */ 396 #define PM_FILT_PLAY ((1 << 0x0A) | (1 << 0x0C) | (1 << 0x0B)) 397 /** filter tick messages (0xF9) */ 398 #define PM_FILT_TICK (1 << 0x09) 399 /** filter undefined FD messages */ 400 #define PM_FILT_FD (1 << 0x0D) 401 /** filter undefined real-time messages */ 402 #define PM_FILT_UNDEFINED PM_FILT_FD 403 /** filter reset messages (0xFF) */ 404 #define PM_FILT_RESET (1 << 0x0F) 405 /** filter all real-time messages */ 406 #define PM_FILT_REALTIME (PM_FILT_ACTIVE | PM_FILT_SYSEX | PM_FILT_CLOCK | \ 407 PM_FILT_PLAY | PM_FILT_UNDEFINED | PM_FILT_RESET | PM_FILT_TICK) 408 /** filter note-on and note-off (0x90-0x9F and 0x80-0x8F */ 409 #define PM_FILT_NOTE ((1 << 0x19) | (1 << 0x18)) 410 /** filter channel aftertouch (most midi controllers use this) (0xD0-0xDF)*/ 411 #define PM_FILT_CHANNEL_AFTERTOUCH (1 << 0x1D) 412 /** per-note aftertouch (0xA0-0xAF) */ 413 #define PM_FILT_POLY_AFTERTOUCH (1 << 0x1A) 414 /** filter both channel and poly aftertouch */ 415 #define PM_FILT_AFTERTOUCH (PM_FILT_CHANNEL_AFTERTOUCH | PM_FILT_POLY_AFTERTOUCH) 416 /** Program changes (0xC0-0xCF) */ 417 #define PM_FILT_PROGRAM (1 << 0x1C) 418 /** Control Changes (CC's) (0xB0-0xBF)*/ 419 #define PM_FILT_CONTROL (1 << 0x1B) 420 /** Pitch Bender (0xE0-0xEF*/ 421 #define PM_FILT_PITCHBEND (1 << 0x1E) 422 /** MIDI Time Code (0xF1)*/ 423 #define PM_FILT_MTC (1 << 0x01) 424 /** Song Position (0xF2) */ 425 #define PM_FILT_SONG_POSITION (1 << 0x02) 426 /** Song Select (0xF3)*/ 427 #define PM_FILT_SONG_SELECT (1 << 0x03) 428 /** Tuning request (0xF6)*/ 429 #define PM_FILT_TUNE (1 << 0x06) 430 /** All System Common messages (mtc, song position, song select, tune request) */ 431 #define PM_FILT_SYSTEMCOMMON (PM_FILT_MTC | PM_FILT_SONG_POSITION | PM_FILT_SONG_SELECT | PM_FILT_TUNE) 432 433 434 PMEXPORT PmError Pm_SetFilter( PortMidiStream* stream, int32_t filters ); 435 436 #define Pm_Channel(channel) (1<<(channel)) 437 /** 438 Pm_SetChannelMask() filters incoming messages based on channel. 439 The mask is a 16-bit bitfield corresponding to appropriate channels. 440 The Pm_Channel macro can assist in calling this function. 441 i.e. to set receive only input on channel 1, call with 442 Pm_SetChannelMask(Pm_Channel(1)); 443 Multiple channels should be OR'd together, like 444 Pm_SetChannelMask(Pm_Channel(10) | Pm_Channel(11)) 445 446 Note that channels are numbered 0 to 15 (not 1 to 16). Most 447 synthesizer and interfaces number channels starting at 1, but 448 PortMidi numbers channels starting at 0. 449 450 All channels are allowed by default 451 */ 452 PMEXPORT PmError Pm_SetChannelMask(PortMidiStream *stream, int mask); 453 454 /** 455 Pm_Abort() terminates outgoing messages immediately 456 The caller should immediately close the output port; 457 this call may result in transmission of a partial midi message. 458 There is no abort for Midi input because the user can simply 459 ignore messages in the buffer and close an input device at 460 any time. 461 */ 462 PMEXPORT PmError Pm_Abort( PortMidiStream* stream ); 463 464 /** 465 Pm_Close() closes a midi stream, flushing any pending buffers. 466 (PortMidi attempts to close open streams when the application 467 exits -- this is particularly difficult under Windows.) 468 */ 469 PMEXPORT PmError Pm_Close( PortMidiStream* stream ); 470 471 /** 472 Pm_Synchronize() instructs PortMidi to (re)synchronize to the 473 time_proc passed when the stream was opened. Typically, this 474 is used when the stream must be opened before the time_proc 475 reference is actually advancing. In this case, message timing 476 may be erratic, but since timestamps of zero mean 477 "send immediately," initialization messages with zero timestamps 478 can be written without a functioning time reference and without 479 problems. Before the first MIDI message with a non-zero 480 timestamp is written to the stream, the time reference must 481 begin to advance (for example, if the time_proc computes time 482 based on audio samples, time might begin to advance when an 483 audio stream becomes active). After time_proc return values 484 become valid, and BEFORE writing the first non-zero timestamped 485 MIDI message, call Pm_Synchronize() so that PortMidi can observe 486 the difference between the current time_proc value and its 487 MIDI stream time. 488 489 In the more normal case where time_proc 490 values advance continuously, there is no need to call 491 Pm_Synchronize. PortMidi will always synchronize at the 492 first output message and periodically thereafter. 493 */ 494 PmError Pm_Synchronize( PortMidiStream* stream ); 495 496 497 /** 498 Pm_Message() encodes a short Midi message into a 32-bit word. If data1 499 and/or data2 are not present, use zero. 500 501 Pm_MessageStatus(), Pm_MessageData1(), and 502 Pm_MessageData2() extract fields from a 32-bit midi message. 503 */ 504 #define Pm_Message(status, data1, data2) \ 505 ((((data2) << 16) & 0xFF0000) | \ 506 (((data1) << 8) & 0xFF00) | \ 507 ((status) & 0xFF)) 508 #define Pm_MessageStatus(msg) ((msg) & 0xFF) 509 #define Pm_MessageData1(msg) (((msg) >> 8) & 0xFF) 510 #define Pm_MessageData2(msg) (((msg) >> 16) & 0xFF) 511 512 typedef int32_t PmMessage; /**< see PmEvent */ 513 /** 514 All midi data comes in the form of PmEvent structures. A sysex 515 message is encoded as a sequence of PmEvent structures, with each 516 structure carrying 4 bytes of the message, i.e. only the first 517 PmEvent carries the status byte. 518 519 Note that MIDI allows nested messages: the so-called "real-time" MIDI 520 messages can be inserted into the MIDI byte stream at any location, 521 including within a sysex message. MIDI real-time messages are one-byte 522 messages used mainly for timing (see the MIDI spec). PortMidi retains 523 the order of non-real-time MIDI messages on both input and output, but 524 it does not specify exactly how real-time messages are processed. This 525 is particulary problematic for MIDI input, because the input parser 526 must either prepare to buffer an unlimited number of sysex message 527 bytes or to buffer an unlimited number of real-time messages that 528 arrive embedded in a long sysex message. To simplify things, the input 529 parser is allowed to pass real-time MIDI messages embedded within a 530 sysex message, and it is up to the client to detect, process, and 531 remove these messages as they arrive. 532 533 When receiving sysex messages, the sysex message is terminated 534 by either an EOX status byte (anywhere in the 4 byte messages) or 535 by a non-real-time status byte in the low order byte of the message. 536 If you get a non-real-time status byte but there was no EOX byte, it 537 means the sysex message was somehow truncated. This is not 538 considered an error; e.g., a missing EOX can result from the user 539 disconnecting a MIDI cable during sysex transmission. 540 541 A real-time message can occur within a sysex message. A real-time 542 message will always occupy a full PmEvent with the status byte in 543 the low-order byte of the PmEvent message field. (This implies that 544 the byte-order of sysex bytes and real-time message bytes may not 545 be preserved -- for example, if a real-time message arrives after 546 3 bytes of a sysex message, the real-time message will be delivered 547 first. The first word of the sysex message will be delivered only 548 after the 4th byte arrives, filling the 4-byte PmEvent message field. 549 550 The timestamp field is observed when the output port is opened with 551 a non-zero latency. A timestamp of zero means "use the current time", 552 which in turn means to deliver the message with a delay of 553 latency (the latency parameter used when opening the output port.) 554 Do not expect PortMidi to sort data according to timestamps -- 555 messages should be sent in the correct order, and timestamps MUST 556 be non-decreasing. See also "Example" for Pm_OpenOutput() above. 557 558 A sysex message will generally fill many PmEvent structures. On 559 output to a PortMidiStream with non-zero latency, the first timestamp 560 on sysex message data will determine the time to begin sending the 561 message. PortMidi implementations may ignore timestamps for the 562 remainder of the sysex message. 563 564 On input, the timestamp ideally denotes the arrival time of the 565 status byte of the message. The first timestamp on sysex message 566 data will be valid. Subsequent timestamps may denote 567 when message bytes were actually received, or they may be simply 568 copies of the first timestamp. 569 570 Timestamps for nested messages: If a real-time message arrives in 571 the middle of some other message, it is enqueued immediately with 572 the timestamp corresponding to its arrival time. The interrupted 573 non-real-time message or 4-byte packet of sysex data will be enqueued 574 later. The timestamp of interrupted data will be equal to that of 575 the interrupting real-time message to insure that timestamps are 576 non-decreasing. 577 */ 578 typedef struct { 579 PmMessage message; 580 PmTimestamp timestamp; 581 } PmEvent; 582 583 /** 584 @} 585 */ 586 /** \defgroup grp_io Reading and Writing Midi Messages 587 @{ 588 */ 589 /** 590 Pm_Read() retrieves midi data into a buffer, and returns the number 591 of events read. Result is a non-negative number unless an error occurs, 592 in which case a PmError value will be returned. 593 594 Buffer Overflow 595 596 The problem: if an input overflow occurs, data will be lost, ultimately 597 because there is no flow control all the way back to the data source. 598 When data is lost, the receiver should be notified and some sort of 599 graceful recovery should take place, e.g. you shouldn't resume receiving 600 in the middle of a long sysex message. 601 602 With a lock-free fifo, which is pretty much what we're stuck with to 603 enable portability to the Mac, it's tricky for the producer and consumer 604 to synchronously reset the buffer and resume normal operation. 605 606 Solution: the buffer managed by PortMidi will be flushed when an overflow 607 occurs. The consumer (Pm_Read()) gets an error message (pmBufferOverflow) 608 and ordinary processing resumes as soon as a new message arrives. The 609 remainder of a partial sysex message is not considered to be a "new 610 message" and will be flushed as well. 611 612 */ 613 PMEXPORT int Pm_Read( PortMidiStream *stream, PmEvent *buffer, int32_t length ); 614 615 /** 616 Pm_Poll() tests whether input is available, 617 returning TRUE, FALSE, or an error value. 618 */ 619 PMEXPORT PmError Pm_Poll( PortMidiStream *stream); 620 621 /** 622 Pm_Write() writes midi data from a buffer. This may contain: 623 - short messages 624 or 625 - sysex messages that are converted into a sequence of PmEvent 626 structures, e.g. sending data from a file or forwarding them 627 from midi input. 628 629 Use Pm_WriteSysEx() to write a sysex message stored as a contiguous 630 array of bytes. 631 632 Sysex data may contain embedded real-time messages. 633 */ 634 PMEXPORT PmError Pm_Write( PortMidiStream *stream, PmEvent *buffer, int32_t length ); 635 636 /** 637 Pm_WriteShort() writes a timestamped non-system-exclusive midi message. 638 Messages are delivered in order as received, and timestamps must be 639 non-decreasing. (But timestamps are ignored if the stream was opened 640 with latency = 0.) 641 */ 642 PMEXPORT PmError Pm_WriteShort( PortMidiStream *stream, PmTimestamp when, int32_t msg); 643 644 /** 645 Pm_WriteSysEx() writes a timestamped system-exclusive midi message. 646 */ 647 PMEXPORT PmError Pm_WriteSysEx( PortMidiStream *stream, PmTimestamp when, unsigned char *msg); 648 649 /** @} */ 650 651 #ifdef __cplusplus 652 } 653 #endif /* __cplusplus */ 654 #endif /* PORT_MIDI_H */