Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

477 lines
21KB

  1. /*! \mainpage The RtMidi Tutorial
  2. <CENTER>\ref intro &nbsp;&nbsp; \ref download &nbsp;&nbsp; \ref start &nbsp;&nbsp; \ref error &nbsp;&nbsp; \ref probing &nbsp;&nbsp; \ref output &nbsp;&nbsp; \ref input &nbsp;&nbsp; \ref virtual &nbsp;&nbsp; \ref compiling &nbsp;&nbsp; \ref debug &nbsp;&nbsp; \ref multi &nbsp;&nbsp; \ref apinotes &nbsp;&nbsp; \ref acknowledge &nbsp;&nbsp; \ref license</CENTER>
  3. \section intro Introduction
  4. RtMidi is a set of C++ classes (RtMidiIn, RtMidiOut and API-specific classes) that provides a common API (Application Programming Interface) for realtime MIDI input/output across Linux (ALSA & Jack), Macintosh OS X (CoreMidi & Jack), and Windows (Multimedia Library & Kernel Streaming) operating systems. RtMidi significantly simplifies the process of interacting with computer MIDI hardware and software. It was designed with the following goals:
  5. <UL>
  6. <LI>object oriented C++ design</LI>
  7. <LI>simple, common API across all supported platforms</LI>
  8. <LI>only two header files and one source file for easy inclusion in programming projects</LI>
  9. <LI>MIDI device enumeration</LI>
  10. </UL>
  11. Where applicable, multiple API support can be compiled and a particular API specified when creating an RtAudio instance.
  12. MIDI input and output functionality are separated into two classes, RtMidiIn and RtMidiOut. Each class instance supports only a single MIDI connection. RtMidi does not provide timing functionality (i.e., output messages are sent immediately). Input messages are timestamped with delta times in seconds (via a \c double floating point type). MIDI data is passed to the user as raw bytes using an std::vector<unsigned char>.
  13. \section whatsnew What's New (Version 2.0)
  14. No incompatable API changes were made in version 2.0, however, support for multiple compiled APIs (where available) was added (see \ref multi). Other changes include: 1. Added Windows Kernel Streaming support (thanks to Sebastien Alaiwan), though not tested in Visual Studio (and timestamping is not implemented); and 2. Support for the IRIX (SGI) operating system was discontinued.
  15. \section download Download
  16. Latest Release (26 July 2012): <A href="http://www.music.mcgill.ca/~gary/rtmidi/release/rtmidi-2.0.1.tar.gz">Version 2.0.1</A>
  17. \section start Getting Started
  18. The first thing that must be done when using RtMidi is to create an instance of the RtMidiIn or RtMidiOut subclasses. RtMidi is an abstract base class, which itself cannot be instantiated. Each default constructor attempts to establish any necessary "connections" with the underlying MIDI system. RtMidi uses C++ exceptions to report errors, necessitating try/catch blocks around many member functions. An RtError can be thrown during instantiation in some circumstances. A warning message may also be reported if no MIDI devices are found during instantiation. The RtMidi classes have been designed to work with "hot pluggable" or virtual (software) MIDI devices, making it possible to connect to MIDI devices that may not have been present when the classes were instantiated. The following code example demonstrates default object construction and destruction:
  19. \code
  20. #include "RtMidi.h"
  21. int main()
  22. {
  23. RtMidiIn *midiin = 0;
  24. // RtMidiIn constructor
  25. try {
  26. midiin = new RtMidiIn();
  27. }
  28. catch (RtError &error) {
  29. // Handle the exception here
  30. error.printMessage();
  31. }
  32. // Clean up
  33. delete midiin;
  34. }
  35. \endcode
  36. Obviously, this example doesn't demonstrate any of the real functionality of RtMidi. However, all uses of RtMidi must begin with construction and must end with class destruction. Further, it is necessary that all class methods that can throw a C++ exception be called within a try/catch block.
  37. \section error Error Handling
  38. RtMidi uses a C++ exception handler called RtError, which is declared
  39. and defined in RtError.h. The RtError class is quite simple but it
  40. does allow errors to be "caught" by RtError::Type. Many RtMidi
  41. methods can "throw" an RtError, most typically if a driver error
  42. occurs or an invalid function argument is specified. There are a
  43. number of cases within RtMidi where warning messages may be displayed
  44. but an exception is not thrown. There is a protected RtMidi method,
  45. error(), that can be modified to globally control how these messages
  46. are handled and reported. By default, error messages are not
  47. automatically displayed in RtMidi unless the preprocessor definition
  48. __RTMIDI_DEBUG__ is defined during compilation. Messages associated
  49. with caught exceptions can be displayed with, for example, the
  50. RtError::printMessage() function.
  51. \section probing Probing Ports
  52. A programmer may wish to query the available MIDI ports before deciding which to use. The following example outlines how this can be done.
  53. \code
  54. // midiprobe.cpp
  55. #include <iostream>
  56. #include <cstdlib>
  57. #include "RtMidi.h"
  58. int main()
  59. {
  60. RtMidiIn *midiin = 0;
  61. RtMidiOut *midiout = 0;
  62. // RtMidiIn constructor
  63. try {
  64. midiin = new RtMidiIn();
  65. }
  66. catch ( RtError &error ) {
  67. error.printMessage();
  68. exit( EXIT_FAILURE );
  69. }
  70. // Check inputs.
  71. unsigned int nPorts = midiin->getPortCount();
  72. std::cout << "\nThere are " << nPorts << " MIDI input sources available.\n";
  73. std::string portName;
  74. for ( unsigned int i=0; i<nPorts; i++ ) {
  75. try {
  76. portName = midiin->getPortName(i);
  77. }
  78. catch ( RtError &error ) {
  79. error.printMessage();
  80. goto cleanup;
  81. }
  82. std::cout << " Input Port #" << i+1 << ": " << portName << '\n';
  83. }
  84. // RtMidiOut constructor
  85. try {
  86. midiout = new RtMidiOut();
  87. }
  88. catch ( RtError &error ) {
  89. error.printMessage();
  90. exit( EXIT_FAILURE );
  91. }
  92. // Check outputs.
  93. nPorts = midiout->getPortCount();
  94. std::cout << "\nThere are " << nPorts << " MIDI output ports available.\n";
  95. for ( unsigned int i=0; i<nPorts; i++ ) {
  96. try {
  97. portName = midiout->getPortName(i);
  98. }
  99. catch (RtError &error) {
  100. error.printMessage();
  101. goto cleanup;
  102. }
  103. std::cout << " Output Port #" << i+1 << ": " << portName << '\n';
  104. }
  105. std::cout << '\n';
  106. // Clean up
  107. cleanup:
  108. delete midiin;
  109. delete midiout;
  110. return 0;
  111. }
  112. \endcode
  113. \section output MIDI Output
  114. The RtMidiOut class provides simple functionality to immediately send messages over a MIDI connection. No timing functionality is provided.
  115. In the following example, we omit necessary error checking and details regarding OS-dependent sleep functions. For a complete example, see the \c midiout.cpp program in the \c tests directory.
  116. \code
  117. // midiout.cpp
  118. #include <iostream>
  119. #include <cstdlib>
  120. #include "RtMidi.h"
  121. int main()
  122. {
  123. RtMidiOut *midiout = new RtMidiOut();
  124. std::vector<unsigned char> message;
  125. // Check available ports.
  126. unsigned int nPorts = midiout->getPortCount();
  127. if ( nPorts == 0 ) {
  128. std::cout << "No ports available!\n";
  129. goto cleanup;
  130. }
  131. // Open first available port.
  132. midiout->openPort( 0 );
  133. // Send out a series of MIDI messages.
  134. // Program change: 192, 5
  135. message.push_back( 192 );
  136. message.push_back( 5 );
  137. midiout->sendMessage( &message );
  138. // Control Change: 176, 7, 100 (volume)
  139. message[0] = 176;
  140. message[1] = 7;
  141. message.push_back( 100 );
  142. midiout->sendMessage( &message );
  143. // Note On: 144, 64, 90
  144. message[0] = 144;
  145. message[1] = 64;
  146. message[2] = 90;
  147. midiout->sendMessage( &message );
  148. SLEEP( 500 ); // Platform-dependent ... see example in tests directory.
  149. // Note Off: 128, 64, 40
  150. message[0] = 128;
  151. message[1] = 64;
  152. message[2] = 40;
  153. midiout->sendMessage( &message );
  154. // Clean up
  155. cleanup:
  156. delete midiout;
  157. return 0;
  158. }
  159. \endcode
  160. \section input MIDI Input
  161. The RtMidiIn class uses an internal callback function or thread to receive incoming MIDI messages from a port or device. These messages are then either queued and read by the user via calls to the RtMidiIn::getMessage() function or immediately passed to a user-specified callback function (which must be "registered" using the RtMidiIn::setCallback() function). We'll provide examples of both usages.
  162. The RtMidiIn class provides the RtMidiIn::ignoreTypes() function to specify that certain MIDI message types be ignored. By default, sysem exclusive, timing, and active sensing messages are ignored.
  163. \subsection qmidiin Queued MIDI Input
  164. The RtMidiIn::getMessage() function does not block. If a MIDI message is available in the queue, it is copied to the user-provided \c std::vector<unsigned char> container. When no MIDI message is available, the function returns an empty container. The default maximum MIDI queue size is 1024 messages. This value may be modified with the RtMidiIn::setQueueSizeLimit() function. If the maximum queue size limit is reached, subsequent incoming MIDI messages are discarded until the queue size is reduced.
  165. In the following example, we omit some necessary error checking and details regarding OS-dependent sleep functions. For a more complete example, see the \c qmidiin.cpp program in the \c tests directory.
  166. \code
  167. // qmidiin.cpp
  168. #include <iostream>
  169. #include <cstdlib>
  170. #include <signal.h>
  171. #include "RtMidi.h"
  172. bool done;
  173. static void finish(int ignore){ done = true; }
  174. int main()
  175. {
  176. RtMidiIn *midiin = new RtMidiIn();
  177. std::vector<unsigned char> message;
  178. int nBytes, i;
  179. double stamp;
  180. // Check available ports.
  181. unsigned int nPorts = midiin->getPortCount();
  182. if ( nPorts == 0 ) {
  183. std::cout << "No ports available!\n";
  184. goto cleanup;
  185. }
  186. midiin->openPort( 0 );
  187. // Don't ignore sysex, timing, or active sensing messages.
  188. midiin->ignoreTypes( false, false, false );
  189. // Install an interrupt handler function.
  190. done = false;
  191. (void) signal(SIGINT, finish);
  192. // Periodically check input queue.
  193. std::cout << "Reading MIDI from port ... quit with Ctrl-C.\n";
  194. while ( !done ) {
  195. stamp = midiin->getMessage( &message );
  196. nBytes = message.size();
  197. for ( i=0; i<nBytes; i++ )
  198. std::cout << "Byte " << i << " = " << (int)message[i] << ", ";
  199. if ( nBytes > 0 )
  200. std::cout << "stamp = " << stamp << std::endl;
  201. // Sleep for 10 milliseconds ... platform-dependent.
  202. SLEEP( 10 );
  203. }
  204. // Clean up
  205. cleanup:
  206. delete midiin;
  207. return 0;
  208. }
  209. \endcode
  210. \subsection cmidiin MIDI Input with User Callback
  211. When set, a user-provided callback function will be invoked after the input of a complete MIDI message. It is possible to provide a pointer to user data that can be accessed in the callback function (not shown here). It is necessary to set the callback function immediately after opening the port to avoid having incoming messages written to the queue (which is not emptied when a callback function is set). If you are worried about this happening, you can check the queue using the RtMidi::getMessage() function to verify it is empty (after the callback function is set).
  212. In the following example, we omit some necessary error checking. For a more complete example, see the \c cmidiin.cpp program in the \c tests directory.
  213. \code
  214. // cmidiin.cpp
  215. #include <iostream>
  216. #include <cstdlib>
  217. #include "RtMidi.h"
  218. void mycallback( double deltatime, std::vector< unsigned char > *message, void *userData )
  219. {
  220. unsigned int nBytes = message->size();
  221. for ( unsigned int i=0; i<nBytes; i++ )
  222. std::cout << "Byte " << i << " = " << (int)message->at(i) << ", ";
  223. if ( nBytes > 0 )
  224. std::cout << "stamp = " << deltatime << std::endl;
  225. }
  226. int main()
  227. {
  228. RtMidiIn *midiin = new RtMidiIn();
  229. // Check available ports.
  230. unsigned int nPorts = midiin->getPortCount();
  231. if ( nPorts == 0 ) {
  232. std::cout << "No ports available!\n";
  233. goto cleanup;
  234. }
  235. midiin->openPort( 0 );
  236. // Set our callback function. This should be done immediately after
  237. // opening the port to avoid having incoming messages written to the
  238. // queue.
  239. midiin->setCallback( &mycallback );
  240. // Don't ignore sysex, timing, or active sensing messages.
  241. midiin->ignoreTypes( false, false, false );
  242. std::cout << "\nReading MIDI input ... press <enter> to quit.\n";
  243. char input;
  244. std::cin.get(input);
  245. // Clean up
  246. cleanup:
  247. delete midiin;
  248. return 0;
  249. }
  250. \endcode
  251. \section virtual Virtual Ports
  252. The Linux ALSA and Macintosh CoreMIDI APIs allow for the establishment of virtual input and output MIDI ports to which other software clients can connect. RtMidi incorporates this functionality with the RtMidiIn::openVirtualPort() and RtMidiOut::openVirtualPort() functions. Any messages sent with the RtMidiOut::sendMessage() function will also be transmitted through an open virtual output port. If a virtual input port is open and a user callback function is set, the callback function will be invoked when messages arrive via that port. If a callback function is not set, the user must poll the input queue to check whether messages have arrived. No notification is provided for the establishment of a client connection via a virtual port.
  253. \section compiling Compiling
  254. In order to compile RtMidi for a specific OS and API, it is necessary to supply the appropriate preprocessor definition and library within the compiler statement:
  255. <P>
  256. <TABLE BORDER=2 COLS=5 WIDTH="100%">
  257. <TR BGCOLOR="beige">
  258. <TD WIDTH="5%"><B>OS:</B></TD>
  259. <TD WIDTH="5%"><B>MIDI API:</B></TD>
  260. <TD WIDTH="5%"><B>Preprocessor Definition:</B></TD>
  261. <TD WIDTH="5%"><B>Library or Framework:</B></TD>
  262. <TD><B>Example Compiler Statement:</B></TD>
  263. </TR>
  264. <TR>
  265. <TD>Linux</TD>
  266. <TD>ALSA Sequencer</TD>
  267. <TD>__LINUX_ALSA__</TD>
  268. <TD><TT>asound, pthread</TT></TD>
  269. <TD><TT>g++ -Wall -D__LINUX_ALSA__ -o midiprobe midiprobe.cpp RtMidi.cpp -lasound -lpthread</TT></TD>
  270. </TR>
  271. <TR>
  272. <TD>Linux or Mac</TD>
  273. <TD>Jack MIDI</TD>
  274. <TD>__UNIX_JACK__</TD>
  275. <TD><TT>jack</TT></TD>
  276. <TD><TT>g++ -Wall -D__UNIX_JACK__ -o midiprobe midiprobe.cpp RtMidi.cpp -ljack</TT></TD>
  277. </TR>
  278. <TR>
  279. <TD>Macintosh OS X</TD>
  280. <TD>CoreMidi</TD>
  281. <TD>__MACOSX_CORE__</TD>
  282. <TD><TT>CoreMidi, CoreAudio, CoreFoundation</TT></TD>
  283. <TD><TT>g++ -Wall -D__MACOSX_CORE__ -o midiprobe midiprobe.cpp RtMidi.cpp -framework CoreMIDI -framework CoreAudio -framework CoreFoundation</TT></TD>
  284. </TR>
  285. <TR>
  286. <TD>Windows</TD>
  287. <TD>Multimedia Library</TD>
  288. <TD>__WINDOWS_MM__</TD>
  289. <TD><TT>winmm.lib, multithreaded</TT></TD>
  290. <TD><I>compiler specific</I></TD>
  291. </TR>
  292. <TR>
  293. <TD>Windows</TD>
  294. <TD>Kernel Streaming</TD>
  295. <TD>__WINDOWS_KS__</TD>
  296. <TD><TT>ks.h, ksmedia.h, setupapi.lib, ksuser.lib, multithreaded</TT></TD>
  297. <TD><I>compiler specific</I></TD>
  298. </TR>
  299. </TABLE>
  300. <P>
  301. The example compiler statements above could be used to compile the <TT>midiprobe.cpp</TT> example file, assuming that <TT>midiprobe.cpp</TT>, <TT>RtMidi.h</TT>, <tt>RtError.h</tt>, and <TT>RtMidi.cpp</TT> all exist in the same directory.
  302. \section debug Debugging
  303. If you are having problems getting RtMidi to run on your system, try passing the preprocessor definition <TT>__RTMIDI_DEBUG__</TT> to the compiler (or define it in RtMidi.h). A variety of warning messages will be displayed that may help in determining the problem. Also try using the programs included in the <tt>test</tt> directory. The program <tt>midiprobe</tt> displays the queried capabilities of all MIDI ports found.
  304. \section multi Using Simultaneous Multiple APIs
  305. Support for each MIDI API is encapsulated in specific MidiInApi or MidiOutApi subclasses, making it possible to compile and instantiate multiple API-specific subclasses on a given operating system. For example, one can compile both the CoreMIDI and Jack support on the OS-X operating system by providing the appropriate preprocessor definitions for each. In a run-time situation, one might first attempt to determine whether any Jack ports are available. This can be done by specifying the api argument RtMidi::UNIX_JACK when attempting to create an instance of RtMidiIn or RtMidiOut. If no available ports are found, then an instance of RtMidi with the api argument RtMidi::MACOSX_CORE can be created. Alternately, if no api argument is specified, RtMidi will first look for CoreMIDI ports and if none are found, then Jack ports (in linux, the search order is ALSA and then Jack; in windows, the search order is WinMM and then WinKS). In theory, it should also be possible to have separate instances of RtMidi open at the same time with different underlying API support, though this has not been tested.
  306. The static function RtMidi::getCompiledApi() is provided to determine the available compiled API support. The function RtMidi::getCurrentApi() indicates the API selected for a given RtMidi instance.
  307. \section apinotes API Notes
  308. RtMidi is designed to provide a common API across the various supported operating systems and audio libraries. Despite that, some issues should be mentioned with regard to each.
  309. \subsection linux Linux:
  310. RtMidi for Linux was developed using the Fedora distribution. Two different MIDI APIs are supported on Linux platforms: <A href="http://www.alsa-project.org/">ALSA</A> and <A href="http://jackit.sourceforge.net/">Jack</A>. A decision was made to not include support for the OSS API because the OSS API provides such limited functionality and because <A href="http://www.alsa-project.org/">ALSA</A> support is now incorporated in the Linux kernel. The ALSA sequencer and Jack APIs allows for virtual software input and output ports.
  311. \subsection macosx Macintosh OS X (CoreAudio):
  312. The Apple CoreMidi API allows for the establishment of virtual input and output ports to which other software applications can connect.
  313. The RtMidi Jack support can be compiled on Macintosh OS-X systems, as well as in Linux.
  314. \subsection windowsds Windows (Multimedia Library):
  315. The \c configure script provides support for the MinGW compiler.
  316. The Windows Multimedia library MIDI calls used in RtMidi do not make use of streaming functionality. Incoming system exclusive messages read by RtMidiIn are limited to a length as defined by the preprocessor definition RT_SYSEX_BUFFER_SIZE (set in RtMidi.cpp). The default value is 1024. There is no such limit for outgoing sysex messages via RtMidiOut.
  317. RtMidi was originally developed with Visual C++ version 6.0.
  318. The \c configure script provides support for the MinGW compiler.
  319. \section acknowledge Acknowledgements
  320. Many thanks to the following people for providing bug fixes and improvements:
  321. <UL>
  322. <LI>Sebastien Alaiwan (Jack memory leaks, Windows kernel streaming)</LI>
  323. <LI>Jean-Baptiste Berruchon (Windows sysex code)</LI>
  324. <LI>Pedro Lopez-Cabanillas (ALSA sequencer API, client naming)</LI>
  325. <LI>Jason Champion (MSW project file for library build)</LI>
  326. <LI>Eduardo Coutinho (Windows device names)</LI>
  327. <LI>Paul Dean (increment optimization)</LI>
  328. <LI>Luc Deschenaux (sysex issues)</LI>
  329. <LI>John Dey (OS-X timestamps)</LI>
  330. <LI>Christoph Eckert (ALSA sysex fixes)</LI>
  331. <LI>Martin Koegler (various fixes)</LI>
  332. <LI>Immanuel Litzroth (OS-X sysex fix)</LI>
  333. <LI>Jon McCormack (Snow Leopard updates)</LI>
  334. <LI>Axel Schmidt (client naming)</LI>
  335. <LI>Alexander Svetalkin (Jack MIDI)</LI>
  336. <LI>Casey Tucker (OS-X driver information, sysex sending)</LI>
  337. <LI>Bastiaan Verreijt (Windows sysex multi-buffer code)</LI>
  338. <LI>Dan Wilcox</LI>
  339. </UL>
  340. \section license License
  341. RtMidi: realtime MIDI i/o C++ classes<BR>
  342. Copyright (c) 2003-2012 Gary P. Scavone
  343. Permission is hereby granted, free of charge, to any person
  344. obtaining a copy of this software and associated documentation files
  345. (the "Software"), to deal in the Software without restriction,
  346. including without limitation the rights to use, copy, modify, merge,
  347. publish, distribute, sublicense, and/or sell copies of the Software,
  348. and to permit persons to whom the Software is furnished to do so,
  349. subject to the following conditions:
  350. The above copyright notice and this permission notice shall be
  351. included in all copies or substantial portions of the Software.
  352. Any person wishing to distribute modifications to the Software is
  353. asked to send the modifications to the original developer so that
  354. they can be incorporated into the canonical version. This is,
  355. however, not a binding provision of this license.
  356. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  357. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  358. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  359. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  360. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  361. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  362. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  363. */